0
while loop if one of data block condition met
I am doing something like: var y=[1,2,3] var x=prompt("what is the number?"); while(x!=y){ /* what I am trying to do is if x does not include any value in y, the while loop will occur. but this line will only make us needed to input all the values in y to come out from this while loop... how should I do this....? */ alert("That's not right!"); var x=prompt("what is the number?"); } alert("Good job!") or this is not possible and i should use switch loop instead of while loop?
1 Resposta
+ 1
Hi. Your "while" is okay for making a loop, but your condition is incorrect. "y" is an array of numbers and it is not right to compare a number with an array, so you need something like a "find" function to determine if "x" is inside of an array or not.
A working code sample:
var y=[1,2,3];
var x=prompt("what is the number?");
while(x!=y.find(n => n == x)) {
alert("That's not right!");
var x=prompt("what is the number?");
}
alert("Good job!");
or you can you an alternative version:
while(y.indexOf(x)!=-1) {