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

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


当前回答

考虑使用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');
// => []

其他回答

const Book = {"Titles":[                          
    {"Book3" : "BULLETIN 3"},
    {"Book1" : "BULLETIN 1"},
    {"Book2" : "BULLETIN 2"}    
]}

const findbystr = function(str) { 
    Book.Titles.forEach(function(data) { 
        if (typeof data[str] != 'undefined') {
            return data[str];
        } 
    }, str) 
}

book = findbystr('Book1');

console.log(book);

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

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

React中内置Array.prototype.map函数的突破

这里要注意的关键是使用语句return to BREAK

let isBroken = false;

colours.map(item => {
    if (isBroken) {
        return;
    }
    if (item.startsWith("y")) {
        console.log("The yessiest colour!");
        isBroken = true;
        return;
    }
});

此处提供更多信息:https://www.codegrepper.com/code-examples/javascript/break+out+of+map+javascript

不幸的是,在这种情况下,如果不使用forEach会更好。而是使用一个常规的for循环,它现在将完全按照您的预期工作。

var array = [1, 2, 3];
for (var i = 0; i < array.length; i++) {
  if (array[i] === 1){
    break;
  }
}

为什么不尝试将函数包装在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中,只需忽略类型。逻辑应该有助于你“打破”你的循环。