【问题标题】:JavaScript function not stopping executionJavaScript函数不停止执行
【发布时间】:2017-09-01 19:24:36
【问题描述】:

我已经验证在某些时候第一个 if 条件为真。函数不应该返回 true 并停止执行吗?然而;在这种情况下,即使在第一个 if 条件为 true 之后,函数也会继续执行,直到 forEach 循环完成,然后每次都返回 false 退出。谁能告诉我错误在哪里?

function checkValid(id){
    pressedButtons.forEach(button => {
        console.log(`ID: ${id} and Button: ${button}`)
        if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
            console.log("IM HERE")
            return true
        }
    })
    return false
}

【问题讨论】:

  • 在回调内部返回不会使外部函数返回。
  • 使用Array.prototype.some,它短路真实值(当然,您仍然必须返回该结果值) .
  • .forEach(button => {}) 位创建一个函数。你是从那个函数返回的,而不是 checkValid。在您的 checkValid 函数中创建一个变量,该变量可以在 forEach 中设置为 true,并在最后返回。
  • 谢谢大家。我现在明白了。

标签: javascript return


【解决方案1】:

您可以在此使用 Promises 来停止进行 foreach 循环。

function checkValid(id){
   var promises= [];
   pressedButtons.forEach(button => {
    return new Promise(function(resolve, reject){
      console.log(`ID: ${id} and Button: ${button}`)
       if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
        console.log("IM HERE")
        resolve(true);
      }
    });
  });
  Promise.race(promises).then(function(result){
    // as soon as any promise resolves it will fall here
  });

}

【讨论】:

    【解决方案2】:

    问题似乎是function scoping/closures

    我添加了一个“isValid”变量,它将在整个 forEach 函数中保持“有效性”。 button => {} 是一个具有自己作用域的函数,它可以在每个 pressedButtons 上运行。 return true 仅从作用域函数返回,而不是从 checkValid 函数返回。

    function checkValid(id){
        var isValid = false;
        pressedButtons.forEach(button => {
            console.log(`ID: ${id} and Button: ${button}`)
            if (id == button+1 || id == button+8 || id == button-1 || id == button-8){
                console.log("IM HERE")
                isValid = true;
            }
        })
        return isValid;
    }
    

    【讨论】:

    • 但这不会打破循环。它仍将在数组末尾继续,然后将返回验证。
    • 这不是一个循环,而是在每个元素上运行单独的函数。 There isn't a built-in break for forEach
    • 您能否详细说明您要完成的工作?更多上下文可能会让我提供更多帮助 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多