Hello What is the problem in my code:
var question = prompt("What is your favorite cars?");
var cars = ["BMW", "Volvo", "Saab", "Ford"];
for (cars = 0; cars <= 3; cars+= 3) {
if (question === cars) {
alert("That is a great car!");
} else {
alert("Nah, there is better choices!");
}
}
It does not activate first alert even if you insert some of the cars from array. But when i change sign from === to !== then first alert is activated.
Now i thought that it goes like this: When i ask the question and user insert answer from my array, then if the answer equal(===) with my array(cars) first alert will run if not(else) then my second alert should run. But in this case only my second alert run whatever is user's answer. I know that there is probably posabilities to do this without "for loop" but i have to try this way. Am I wrong with code or my logic here is wrong?
You might want to take a look here. The way you iterate over the items in the cars array is incorrect.
var question = prompt("What is your favorite cars?");
var cars = ["BMW", "Volvo", "Saab", "Ford"];
for (i = 0; i < cars.length; i++) {
if (question === cars[i]) {
alert("That is a great car!");
break;
} else {
alert("Nah, there is better choices!");
break;
}
}
No need for loop:
var question = prompt("What is your favorite cars?");
var cars = ["BMW", "Volvo", "Saab", "Ford"];
if (cars.indexOf(question)!==-1) {
alert("That is a great car!");
} else {
alert("Nah, there is better choices!");
}
You can use indexOf method to search array...
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