Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop and prompt

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?

like image 803
gojic Avatar asked Dec 12 '25 08:12

gojic


2 Answers

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;
  }
}
like image 171
Thomas Devos Avatar answered Dec 15 '25 16:12

Thomas Devos


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

like image 44
sinisake Avatar answered Dec 15 '25 16:12

sinisake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!