Note that there are some explanatory texts on larger screens.

plurals
  1. POJavaScript looping through array
    primarykey
    data
    text
    <p>I'm trying to complete this assignment, I've got the code set up, however, there's a problem.</p> <p><strong>The assignment</strong>: "Create an array with seven string values, initialized to the names of these stars: Polaris, Aldebaran, Deneb, Vega, Altair, Dubhe, and Regulus. Create an array with seven additional string values, initialized to the names of the constellations in which the stars are found: Ursa Minor, Taurus, Cygnus, Lyra, Aquila, Ursa Major, and Leo. Next, create a function that accepts a single string parameter. Within the function, iterate through the first array, searching for the star. When the star is found, return the value contained in that index within the second array. In other words, return the constellation name for that star. Use a prompt to gather the name of the star from the visitor, and then call the function with that input. Don’t forget to include code that executes when the star isn’t found. Display the result on the screen."</p> <p><strong>The code</strong>:</p> <pre><code>var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"]; var stars2 = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major", "Leo"]; function processStar(starName){ for (var i=0; i &lt; stars.length; i++) { if(starName == stars[i]){ return stars2[i]; } else { return "No star found!"; } } } var getStar = prompt("Input the star name."); var result = processStar(getStar); alert(result); </code></pre> <p><strong>The problem</strong>:</p> <p>This code works only for the first value in the stars array. Anything other than the first element of that array ("Polaris"), the function returns with false value.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload