【问题标题】:Javascript returning in forEach loopJavascript 在 forEach 循环中返回
【发布时间】:2019-05-22 05:35:48
【问题描述】:

我经常遇到这种情况,只是想知道我的解决方案是否是最好的,以及是否有更好的解决方案。很多情况下我有一个forEach 循环,我想检查是否有任何值不正确,如果是,则结束代码(return)。这是我在没有循环的情况下会做的事情:

const email = '...';
if (email.isInvalid) return;

在循环中我会这样做:

const emailList ['...', '...', '...'];
const emailErrors = [];

emailList.forEach((element) => {
    // if (element.isInvalid) return; // This won't work here, it just ends this loop instance, which is my problem
    if (element.isInvalid) emailErrors.push(element);
});

if (emailErrors.length > 0) return; // This will end the code correctly

有没有更好的方法来实现这个想法?使用try, catch 或其他?

【问题讨论】:

标签: javascript foreach try-catch


【解决方案1】:

您不能从forEach 发送break。它将在数组的每个元素上运行。您可以使用some 来检查是否至少有一项是isInvalid。一旦找到带有isInvalid = true 的项目,这将短路

if (emailList.some(element => element.isInvalid))
  return

【讨论】:

    【解决方案2】:

    您的 forEach 对每个元素执行 arrow function 并且不检查其结果。我不推荐使用try-catch,因为它很慢。尝试将for-ofreturn 一起使用(或break 不返回但只中断循环并继续执行for 以下的代码)

    function start() {
      const emailList = ['abc@test.com', 'invalid 1', 'invalid 2'];
      const emailErrors = [];
    
      for(let element of emailList)
      {
        console.log(element);
        if(!/@/.test(element)) return;  // some validation (missing @ char)
      };
    
    }
    
    start();

    【讨论】:

      【解决方案3】:

      您可以使用 Array​.prototype​.every()。

      every() 方法测试数组中的所有元素是否通过提供的函数实现的测试。它返回一个布尔值。

      function validateEmailList(element) {
        return element.isInvalid;
      }
      
      console.log(emailList.every(validateEmailList));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-06
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 2021-08-12
        • 2017-03-10
        • 2020-02-28
        • 2018-10-08
        相关资源
        最近更新 更多