由于某种原因,这段代码不断循环。目的是将平方英尺或米转换为另一种测量单位。我希望代码循环并仅在用户不输入“米”或“英尺”一词时再次提示用户,而是无限循环并导致 chrome 崩溃。我究竟做错了什么?谢谢!
while (whichunit !== "meter" || "foot"){
var whichunit = prompt("Would you like to convert from square meter or square foot? Enter meter/foot below");
if(whichunit == "meter"){
var unitnum = prompt("What is the price per meter?");
var matchboxindex = unitnum * 0.0015;
console.log("The match box index is " + matchboxindex);
}
else if(whichunit == "foot"){
var unitnum = prompt("What is the price per foot?");
var matchboxindex = unitnum *0.0015 * 10.7639;
console.log("The match box index is " + matchboxindex);
}
else {
console.log("Please enter either foot or meter");
}
}
最佳答案
while (whichunit !== "meter" || "foot"){
var whichunit = prompt("Would you like to convert from square meter or square foot? Enter meter/foot below");
无限循环是因为'||'后面的条件(应该是“&”)只是“foot”,它的计算结果始终为 true。所以只需重写为:
var whichunit = '';
while (whichunit !== "meter" && whichunit !== "foot"){
whichunit = prompt("Would you like to convert from square meter or square foot? Enter meter/foot below");
...
关于Javascript:While循环不会停止 - 转换单位以给出空间面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41598094/