[1,2,3].forEach(function(el) {
    if(el === 1) break;
});

如何在JavaScript中使用新的forEach方法实现这一点?我尝试过返回;,return false;和断裂。break崩溃,return只会继续迭代。


当前回答

简短回答:用于。。。为此中断或更改代码以避免中断forEach。不要使用.some()或.every()来模拟。。。打破重写代码以避免。。。中断循环,或用于。。。打破每次你使用这些方法。。。上帝杀死了小猫。

长答案:

.some()和.every()都返回布尔值,如果有任何元素的传递函数返回true,.some(返回true,如果有元素的传递的函数返回false,则every返回false。这就是函数的含义。使用函数来实现它们并不意味着什么,这比使用表来布局而不是CSS要糟糕得多,因为这会让所有阅读代码的人感到沮丧。

此外,使用这些方法的唯一可能方法是。。。break替代方法是产生副作用(在.some()回调函数之外更改一些vars),这与for。。。打破

因此,使用.some()或.every()作为。。。断环替代方案并没有副作用,这对。。。打破,这是令人沮丧的,所以这不是更好的。

您可以随时重写代码,这样就不需要。。。打破您可以使用.filter()过滤数组,也可以使用.slice()等拆分数组,然后使用.forEach()或.map()处理该部分数组。

其他回答

简短回答:用于。。。为此中断或更改代码以避免中断forEach。不要使用.some()或.every()来模拟。。。打破重写代码以避免。。。中断循环,或用于。。。打破每次你使用这些方法。。。上帝杀死了小猫。

长答案:

.some()和.every()都返回布尔值,如果有任何元素的传递函数返回true,.some(返回true,如果有元素的传递的函数返回false,则every返回false。这就是函数的含义。使用函数来实现它们并不意味着什么,这比使用表来布局而不是CSS要糟糕得多,因为这会让所有阅读代码的人感到沮丧。

此外,使用这些方法的唯一可能方法是。。。break替代方法是产生副作用(在.some()回调函数之外更改一些vars),这与for。。。打破

因此,使用.some()或.every()作为。。。断环替代方案并没有副作用,这对。。。打破,这是令人沮丧的,所以这不是更好的。

您可以随时重写代码,这样就不需要。。。打破您可以使用.filter()过滤数组,也可以使用.slice()等拆分数组,然后使用.forEach()或.map()处理该部分数组。

尝试“查找”:

var myCategories = [
 {category: "start", name: "Start", color: "#AC193D"},
 {category: "action", name: "Action", color: "#8C0095"},
 {category: "exit", name: "Exit", color: "#008A00"}
];

function findCategory(category) {
  return myCategories.find(function(element) {
    return element.category === category;
  });
}

console.log(findCategory("start"));
// output: { category: "start", name: "Start", color: "#AC193D" }

为什么不尝试将函数包装在Promise中?

我提出这个问题的唯一原因是我在API中使用了一个函数,该函数的作用方式与forEach类似。我不希望它在找到值后继续迭代,我需要返回一些东西,所以我只需要解析Promise并以这种方式执行。

traverseTree(doc): Promise<any> {
  return new Promise<any>((resolve, reject) => {
    this.gridOptions.api.forEachNode((node, index) => {
    //the above function is the one I want to short circuit.
      if(node.data.id === doc.id) {
        return resolve(node);
      }
    });
  });
}

那么你所需要做的就是做一些事情,比如

this.traverseTree(doc).then((result) => {
   this.doSomething(result);
});

我上面的例子是在typescript中,只需忽略类型。逻辑应该有助于你“打破”你的循环。

如果您想使用Dean Edward的建议并抛出StopIteration错误以跳出循环而不必捕获错误,则可以使用以下函数(最初来自此处):

// Use a closure to prevent the global namespace from be polluted.
(function() {
  // Define StopIteration as part of the global scope if it
  // isn't already defined.
  if(typeof StopIteration == "undefined") {
    StopIteration = new Error("StopIteration");
  }

  // The original version of Array.prototype.forEach.
  var oldForEach = Array.prototype.forEach;

  // If forEach actually exists, define forEach so you can
  // break out of it by throwing StopIteration.  Allow
  // other errors will be thrown as normal.
  if(oldForEach) {
    Array.prototype.forEach = function() {
      try {
        oldForEach.apply(this, [].slice.call(arguments, 0));
      }
      catch(e) {
        if(e !== StopIteration) {
          throw e;
        }
      }
    };
  }
})();

上述代码将使您能够运行以下代码,而无需执行自己的try-catch子句:

// Show the contents until you get to "2".
[0,1,2,3,4].forEach(function(val) {
  if(val == 2)
    throw StopIteration;
  alert(val);
});

需要记住的一点是,如果Array.prototype.forEach函数已经存在,则只会更新它。如果它还不存在,它将不会修改它。

如前所述,不能破坏.forEach()。

这里有一种使用ES6迭代器进行foreach的稍微更现代的方法。允许您在迭代时直接访问索引/值。

const array = ['one', 'two', 'three'];

for (const [index, val] of array.entries()) {
  console.log('item:', { index, val });
  if (index === 1) {
    console.log('break!');
    break;
  }
}

输出:

item: { index: 0, val: 'one' }
item: { index: 1, val: 'two' }
break!

链接

Array.prototype.entries()迭代器和发电机解构赋值