【问题标题】:How to stop loop if only one of these isn't true?如果其中只有一个不正确,如何停止循环?
【发布时间】:2022-01-12 15:39:35
【问题描述】:

如果激活自动模式,我有一个 while 函数将在自动模式下运行 (checkBox.checked)

问题是这个代码只有在 a 和 b 都大于我的游戏限制 # (bestof.value) 时才会停止。我希望它在其中只有一个不正确时停止。

当我使用while(a || b < bestof.value) 时,它会超时,直到堆栈达到其限制。它也不返回任何值。

if ( checkBox.checked == true ) {
    while( a && b < bestof.value ) {
       myFunction();
    }
};

知道如何解决这个问题吗?

【问题讨论】:

  • while (a &lt; bestof.value &amp;&amp; b &lt; bestof.value)。 Javascript 不像英语那样工作。
  • “一旦 a 和 b 都大于我的游戏限制” - 这是不正确的。当atruthyb 等于或大于bestof.value 时,循环将结束
  • 请注意,您的括号不匹配(两个左大括号,在if 的末尾,在while 的末尾,以及一个右大括号)。

标签: javascript while-loop


【解决方案1】:

你犯的错误:

  1. while我希望循环在 a 或 b 之一大于我的游戏限制时停止”的条件与“运行循环直到 a 和 b 都小于限制":
while(a < bestof.value && b < bestof.value) { ... }
  1. 无需自行将if 条件转换/比较为布尔值,JS 会自动完成,这就足够了:
if (checkBox.checked) { ... }
  1. 您错过了“}”。如果您的 IDE/编辑器不这样做,请始终比较左括号和右括号的数量。
if (checkBox.checked == true){
    while(a && b < bestof.value) {
        myFunction();
//   ↑ here you forget to close while body
};

另外:您始终可以使用 break 关键字停止任何循环:

white(condition) {
  if (needToStop) { break; }
}

结论:您的代码应如下所示:

if (checkBox.checked) {
    while(a < bestof.value && b < bestof.value) {
        myFunction();
    }
};

【讨论】:

    【解决方案2】:

    你是想说 a 和 b 应该小于 bestof.value 吗?

    不幸的是,这不是语法的工作方式,&& 分隔语句,所以基本上你是在说 a 为真而 b 小于...

    你需要的是这个:

    if (checkBox.checked == true){
        while(a < bestof.value && b < bestof.value){
        myFunction();
    };
    

    正如您正确意识到的那样,您的代码只会在 a 和 b 超过该值时停止,因为它会检查 a 是否存在并且 b 是否超过该值,所以基本上您的触发器是当 b 超过该值时。

    另一个例子:

    let a = 1
    let b
    if (a) {
      console.log("a exists")
    }
    if (b) {
      console.log("b exists")
    }

    如您所见,“b 存在”没有被打印出来,这基本上是您在 &amp;&amp; 之前询问您的 while 循环,如果 a 存在...

    【讨论】:

    • 2 个获胜值(a 和 b)都应
    • 无论学习过程处于哪个阶段,花时间学习新事物的人都不是无知
    猜你喜欢
    • 1970-01-01
    • 2020-05-05
    • 2023-01-20
    • 2022-01-11
    • 2020-11-23
    • 2021-05-23
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多