Short circuit Array.forEach like calling break

2018-12-31 00:57发布

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

How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.

28条回答
素衣白纱
2楼-- · 2018-12-31 01:34

If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):

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

The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:

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

One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.

查看更多
初与友歌
3楼-- · 2018-12-31 01:34

If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..

[1,3,4,5,6,7,8,244,3,5,2].forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

Or with a clone:

var x = [1,3,4,5,6,7,8,244,3,5,2];

x.slice().forEach(function (item, index, arr) {
  if (index === 3) arr.length = 0;
});

Which is a far better solution then throwing random errors in your code.

查看更多
倾城一夜雪
4楼-- · 2018-12-31 01:34

you can follow the code below which works for me:

 var     loopStop = false;
YOUR_ARRAY.forEach(function loop(){
    if(loopStop){ return; }
    if(condition){ loopStop = true; }
});
查看更多
浮光初槿花落
5楼-- · 2018-12-31 01:35

You can use every method:

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

ES6

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

for old browser support use:

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

more details here.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 01:36

I prefer to use for in

var words = ['a', 'b', 'c'];
var text = '';
for (x in words) {
    if (words[x] == 'b') continue;
    text += words[x];
}
console.log(text);

for in works much like forEach, and you can add return to exit function inside. Better performance too.

查看更多
临风纵饮
7楼-- · 2018-12-31 01:37

Use the array.prototype.every function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network

查看更多
登录 后发表回答