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

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


当前回答

我提出的另一个概念是:

函数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();}});

其他回答

我为此使用了nullhack,它试图访问null的属性,这是一个错误:

try {
  [1,2,3,4,5]
  .forEach(
    function ( val, idx, arr ) {
      if ( val == 3 ) null.NULLBREAK;
    }
  );
} catch (e) {
  // e <=> TypeError: null has no properties
}
//

您可以使用每种方法:

[1,2,3].every(function(el) {
    return !(el === 1);
});

ES6

[1,2,3].every( el => el !== 1 )

对于旧浏览器支持使用:

if (!Array.prototype.every)
{
  Array.prototype.every = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this &&
          !fun.call(thisp, this[i], i, this))
        return false;
    }

    return true;
  };
}

更多详情请点击此处。

在其他网站上找到此解决方案。您可以在try/catch场景中包装forEach。

if(typeof StopIteration == "undefined") {
 StopIteration = new Error("StopIteration");
}

try {
  [1,2,3].forEach(function(el){
    alert(el);
    if(el === 1) throw StopIteration;
  });
} catch(error) { if(error != StopIteration) throw error; }

此处提供更多详细信息:http://dean.edwards.name/weblog/2006/07/enum/

没有内置的功能可以为Each进行破解。要中断执行,必须抛出某种异常。

var BreakException={};尝试{[1,2,3]对于每个(函数(el){控制台日志(el);如果(el==2)抛出BreakException;});}捕获(e){如果(e!==BreakException)抛出e;}

JavaScript异常并不漂亮。如果你真的需要打破传统的for循环,那么它可能更合适。

使用数组#some

而是使用Array#some:

[1,2,3]一些(函数(el){控制台日志(el);返回el==2;});

这之所以有效,是因为只要按数组顺序执行的任何回调返回true,就会立即返回true,从而缩短其余回调的执行。

有些,它的逆every(返回false时停止)和forEach都是ECMAScript第五版方法,需要在缺少它们的浏览器上添加到Array.prototype中。

使用数组#间隔

[1,2,3]每(v=>{如果(v>2){return false//“break”}控制台日志(v);return true//如果不中断,则必须返回true});

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);