How to short circuit Array.forEach like calling break?
[1,2,3].forEach(function(el) {
if(el === 1) break;
});
我怎样才能在JavaScript中使用新的forEach
方法?
There's no built-in ability to break
in forEach
. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
You can use every method:
[1,2,3].every(function(el) {
return !(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.
There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let el of arr) {
console.log(el);
if (el === 5) {
break;
}
}
链接地址: http://www.djcxy.com/p/1886.html