变量时间似乎没有定义,但作为js的新手,无法理解问题的所在。尝试全局声明var时间,然后在条件内增加,但不工作。
var j1 = 0;
var j2 = 0;
var j3 = 4;
var time;
if((j1||j2||j3)>=3){
time+5000;
while(time === 30000){
if(j1>=3){
alert("Junction 1 is flooded");
}else if(j2>=3){
alert("Junction 2 is flooded");
}else if(j3>=3){
alert("Junction 3 is flooded");
}else if ((j1&&j2)>=3){
alert("Junction 1 & 2 are flooded");
}else if ((j1&&j3)>=3){
alert("Junction 1 & 3 are flooded");
}else if ((j2&&j3)>=3){
alert("Junction 2 & 3 are flooded");
}else if ((j1&&j3)>=3){
alert("Junction 1 & 3 are flooded");
}else if ((j1&&j3&&j2)>=3){
alert("All 3 junctions are flooded");
}
}
}
发布于 2018-11-21 16:25:13
time+5000;没有为您做任何事情,因为time是undefined,因为您所做的只是声明,但没有使用:
var time; // Declared but not initialized === undefined你不能用undefined做数学。
此外,您没有捕获数学操作的结果。
Make it:
var time = 0; // Declared and initialized ;),然后:
time = time + 5000; // Assign result of expression back to variable接下来,您的if 条件是不正确的。必须单独对多个值进行测试,因此如下:
if((j1||j2||j3)>=3){需要变成这样:
if(j1 >= 3 || j2 >= 3 || j3 >=3){最后,按照现在的代码方式,time只会增加一次,达到5000的值,因此永远不会进入while循环。然后,即使进入您的循环,您也不会在其中修改time的值,因此循环永远不会结束。您需要设置某种条件来检查,以确定循环是否应该继续。应该是这样的:
while(time < 50000){
if(time === 30000){
if(j1 >= 3){
alert("Junction 1 is flooded");
}else if(j2 >= 3){
alert("Junction 2 is flooded");
}else if(j3 >= 3){
alert("Junction 3 is flooded");
}else if (j1 >= 3 && j2 >=3){
alert("Junction 1 & 2 are flooded");
}else if (j1 >= 3 && j3 >= 3){
alert("Junction 1 & 3 are flooded");
}else if (j2 >= 3 && j3 >=3){
alert("Junction 2 & 3 are flooded");
}else if (j1 >= 3 && j3>=3){
alert("Junction 1 & 3 are flooded");
}else if (j1 >=3 && j3 >=3 &&j2 >=3){
alert("All 3 junctions are flooded");
}
}
time = time + 5000; // <-- You need to create a situation where the loop can end!
}所以,把它们放在一起:
var j1 = 0;
var j2 = 0;
var j3 = 4;
var time = 0;
if(j1 >= 3 || j2 >= 3 || j3 >=3){
while(time < 50000){
// Check what time is with an "if"
if(time === 30000){
if(j1 >= 3){
alert("Junction 1 is flooded");
}else if(j2 >= 3){
alert("Junction 2 is flooded");
}else if(j3 >= 3){
alert("Junction 3 is flooded");
}else if (j1 >= 3 && j2 >=3){
alert("Junction 1 & 2 are flooded");
}else if (j1 >= 3 && j3 >= 3){
alert("Junction 1 & 3 are flooded");
}else if (j2 >= 3 && j3 >=3){
alert("Junction 2 & 3 are flooded");
}else if (j1 >= 3 && j3>=3){
alert("Junction 1 & 3 are flooded");
}else if (j1 >=3 && j3 >=3 &&j2 >=3){
alert("All 3 junctions are flooded");
}
}
time = time + 5000; // <-- You need to create a situation where the loop can end!
}
}
发布于 2018-11-21 16:25:36
使用time+=5000;而不是time+5000;
发布于 2018-11-21 16:26:48
您应该将时间设置为等于0,并使用+=来增加时间。
var time=0;
if(j1>=3||j2>=3||j3>=3){
time+=5000;只编写var time;和var time = undefined是一样的,您不能在未定义的情况下执行数学操作。您需要初始化变量。
要增加时间变量,您需要将其设置为5000加上自身或time = time + 5000或简写为time += 5000。
https://stackoverflow.com/questions/53416402
复制相似问题