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

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


当前回答

尝试“查找”:

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" }

其他回答

我提出的另一个概念是:

函数forEach(数组,cb){var shouldBreak;函数_break(){shouldBreak=true;}for(var i=0,bound=array.length;i<bound;++i){if(shouldBreak){break;}cb(array[i],i,array,_break);}}//用途forEach([‘a’,‘b’,‘c’,‘d’,‘e’,‘f’],函数(char,i,array,_break){console.log(i,char);如果(i===2){_break();}});

现在,在ECMAScript2015(也称为ES6)中使用新的for of循环有更好的方法来实现这一点。例如,此代码不打印数字5之后的数组元素:

常量arr=[0,1,2,3,4,5,6,7,8,9,10];for(arr常量){控制台日志(el);如果(el==5){打破}}

从文档中:

两者都用于。。。为。。。of语句对某些内容进行迭代。它们之间的主要区别在于迭代的内容。用于。。。in语句按原始插入顺序迭代对象的可枚举财产。用于。。。of语句迭代可迭代对象定义要迭代的数据。

迭代中需要索引吗?可以使用Array.entries():

for (const [index, el] of arr.entries()) {
  if ( index === 5 ) break;
}

我使用return false,这对我有用。

这不是最有效的,因为你仍然循环所有元素,但我认为这可能值得考虑非常简单的:

let keepGoing = true;
things.forEach( (thing) => {
  if (noMore) keepGoing = false;
  if (keepGoing) {
     // do things with thing
  }
});

考虑使用jquery的each方法,因为它允许在回调函数中返回false:

$.each(function(e, i) { 
   if (i % 2) return false;
   console.log(e)
})

Lodash库还提供了takeWhile方法,可以与map/reduce/fold等链接:

var users = [
  { 'user': 'barney',  'active': false },
  { 'user': 'fred',    'active': false },
  { 'user': 'pebbles', 'active': true }
];

_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']

// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']

// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []