【问题标题】:JS while loop condition [duplicate]JS while循环条件[重复]
【发布时间】:2022-07-06 02:52:07
【问题描述】:

JS 猜数字游戏。 一切都检查了,但代码卡在循环中,而 (go!="yes" || go!="no" ) 甚至输入是或否。我错过了什么?

// Ask user to retry
while (guess != random) {
    let go = prompt("wrong guess -_-\nWould you like to retey? (yes/no)");
    console.log(go)
    while (go!="yes" || go!="no" ) {
        go = prompt("You must enter yes or no\nWould you like to retey? (yes/no)");
        console.log(go,8)
    }
    if (go == "no") {
        break;
    }
    guess = parseInt(prompt("Enter your guess"));
}

【问题讨论】:

  • go = "no" 不是“是”,因此条件通过。当go = "yes" 不是“否”时,条件通过。当go = "anything else" 不是“是”时,条件通过。

标签: javascript


【解决方案1】:

好的,鉴于你的表达方式。

go!="yes" || go!="no"

假设gowibble

true || true == true

现在假设go"yes"

false || true == true

现在假设go"no"

true || false == true

没有什么条件不适合true


你需要在这里使用&&

或者,您可以使用数组的includes 方法,这在查看代码时更容易理解,当您需要测试更长的值列表时更方便:

if ( !["yes", "no"].includes(go) ) 

【讨论】:

  • 我的天啊,我太笨了,是的,我应该使用 &&,虽然两者都不是真的 - 循环
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 2018-10-02
  • 2018-09-22
  • 2021-11-28
  • 2016-03-30
相关资源
最近更新 更多