Why is my for loop stuck on the second option?

Viewed 134

First project - need to pull from nested arrays for a quiz but loop is stuck somehow on the second position in the array and is skipping the first. also is stuck in an infinite loop -

var quiz = [ 
             [ "what color is the sky?" , "blue" ],
             [ "what color are most apples?", "red" ],
             [ "what color is coffee?" , "black" ]
];

var i;
for ( i = 0; i < 3; i++) {
  if (i = 0) { 
    var ans1 = prompt(quiz[0][0]);
  } else if (i = 1) {
    var ans2 = prompt(quiz[1][0]);
  } else {
    var ans3 = prompt(quiz[2][0]);
  }
}


document.write(ans1 + ans2 + ans3);

My logic is that if i = 0 from the start it should run the first prompt then finish the loop adding 1 to the i variable, then run the second prompt etc.

I tried looking it up, tried a while loop, tried changing the last else to else if (i = 2).

4 Answers

You need to change if (i = 0) to if (i == 0). In Javascript and many other programming languages, = means assignment, but == means comparison. Since you're trying to compare i to an integer, you want the comparison operator, rather than the assignment operator.

A single = is an assignment. You want to have a double equation to do comparison:

var quiz = [ 
             [ "what color is the sky?" , "blue" ],
             [ "what color are most apples?", "red" ],
             [ "what color is coffee?" , "black" ]
];

var i;
for ( i = 0; i < 3; i++) {
  if (i == 0) { 
    var ans1 = prompt(quiz[0][0]);
  } else if (i == 1) {
    var ans2 = prompt(quiz[1][0]);
  } else {
    var ans3 = prompt(quiz[2][0]);
  }
}


document.write(ans1 + ans2 + ans3);

The problem is with the = operator use == operator or better yet ===, but again You don't need the loop or the conditions in this case.

var quiz = [ 
             [ "what color is the sky?" , "blue" ],
             [ "what color are most apples?", "red" ],
             [ "what color is coffee?" , "black" ]
];

var ans1 = prompt(quiz[0][0]);
var ans2 = prompt(quiz[1][0]);
var ans3 = prompt(quiz[2][0]);

document.write(ans1 + ans2 + ans3);
if (i = 0){
}

you are assigning value to variable i instead of comparing it. use "==" for comparing the two values in if conditon.

if (i == 0){
    }
Related