Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my for loop stuck on the second option?

Tags:

javascript

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).

like image 740
jwhunt1 Avatar asked Oct 07 '19 16:10

jwhunt1


Video Answer


2 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.

like image 149
karthikdivi Avatar answered Sep 28 '22 04:09

karthikdivi


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);
like image 41
Unamata Sanatarai Avatar answered Sep 28 '22 04:09

Unamata Sanatarai