可变时间似乎是不确定的,但是作为js的新手,他无法理解问题所在。试图全局声明var time,然后在内部条件下递增,但不起作用。
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");
}
}
}
答案 0 :(得分:0)
time+5000;
不会为您做任何事情,因为time
是undefined
,因为您所做的全部是声明的,但未使用以下方法初始化它:
var time; // Declared but not initialized === undefined
,并且您无法使用undefined
进行数学运算。
此外,您没有捕获数学运算的结果。
设置:
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!
}
}
答案 1 :(得分:0)
使用time+=5000;
代替time+5000;
答案 2 :(得分:0)
您应该将时间设置为0,然后使用+ =递增时间。
var time=0;
if(j1>=3||j2>=3||j3>=3){
time+=5000;
仅编写var time;
与var time = undefined
相同,并且您不能对未定义的对象执行数学运算。您需要初始化变量。
要增加时间变量,您需要将其设置为5000加自身或time = time + 5000
或简写time += 5000
。