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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With