Reputation: 1
well i was trying to write a for condition in java script when suddenly it so happened that i started getting the message 3 to 4 times instead of just once i first defined both the variables and then wrote a for code in which i nested and if else statement and then closed all of them but it so happens that there is an infinite loop created.I tried the following:-
function setValue(){
myVariable1= document.forms["myform"]["ram"].value;
var xuv = ["go", "no", "yes"];
for (i=0;i<xuv.length;i++)
{
if (myVariable1 === xuv[0])
{
alert("yes this game can run")
}
else
{
alert("No, This game cannot run")
}
}
};
Upvotes: 0
Views: 128
Reputation: 10249
function setValue(){
myVariable1= document.forms["myform"]["ram"].value;
var xuv = ["go", "no", "yes"];
var canRun = false; //i asume the programm can't run
for (i=0;i<xuv.length;i++)
{
if (myVariable1 === xuv[i]) //changed from 0 to i here
{
//but when my input is in the array it can run
canRun = true;
}
}
if (canRun)
{
alert("yes this game can run");
}
else
{
alert("No, This game cannot run");
}
};
your problem was, that you checked 3 times if your input is go
.
What i think you are trying to do is check if your input is in the array.
You also want to print just one alert which i do in the if-block
after the loop
Upvotes: 0
Reputation: 28558
Because you are comparing same index in a loop so condition always gets true and its alert, even condition fails it will alert 3 times until you break the loop or it reaches the stop condition:
function setValue(){
var myVariable1= document.forms["myform"]["ram"].value;//add var otherwise it would expect it as global
var xuv = ["go", "no", "yes"];
for (var i=0;i<xuv.length;i++)
{
if (myVariable1 === xuv[i]) //changed from 0 to i here
{
alert("yes this game can run");
return;
}
else
{
alert("No, This game cannot run");
return;
}
}
};
Upvotes: 0
Reputation: 218887
I think you meant to index the array:
if (myVariable1 === xuv[i])
Currently you're just checking xuv[0]
with each iteration of the loop. So if xuv[0]
satisfies your condition and the loop iterates a few times, you'll see your message a few times. If it doesn't, you'll never see it.
If it was an infinite loop then you'd never stop seeing it...
Upvotes: 2