Javascript:While循环不会停止 - 转换单位以给出空间面积

标签 javascript

由于某种原因,这段代码不断循环。目的是将平方英尺或米转换为另一种测量单位。我希望代码循环并仅在用户不输入“米”或“英尺”一词时再次提示用户,而是无限循环并导致 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/

相关文章:

JavaScript 警报没有响应

javascript - JavaScript 回调函数中的变量总是在循环中获取最后一个值?

JavaScript 操作系统检测 - 多个 Windows XP 版本?

javascript - 前缀零改变数字加法的输出

javascript - Ember.Select View 在更改内容数组后未更新

javascript - JQuery - 获取输入 ='file' 内的所有文件名

javascript - 在根上表达动态路由

javascript - 消除 Javascript 中的按键延迟

javascript - 如何使用 Javascript 访问本地 JSON 文件?

javascript - sails 调试命令在 Sails.js 中不起作用