3

I'm trying to complete this assignment, I've got the code set up, however, there's a problem.

The assignment: "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."

The 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 < 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);

The problem:

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.

1
  • To map a star to its constellation an associative array makes more sense.
    – mike jones
    Commented Nov 27, 2011 at 16:08

2 Answers 2

5

Your conditional statement is wrong. Try this out.

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 < stars.length; i++) {
    if(starName == stars[i]){
        return stars2[i];
    } 
}

return "No star found!";

}

var getStar = prompt("Input the star name.");
var result = processStar(getStar);
alert(result);
5

Inside your loop body, you're always returning a value, so the loop body will only ever execute once.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.