[1,2,3].forEach(function(el) {
if(el === 1) break;
});
Copy Code How can we do this using the new forEach
method in JavaScript ?
There's no built-in option to break
in forEach
. To interrupt execution we would have to throw an exception of some sort.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el)
{
console.log(el);
if (el === 2) throw BreakException;
});
}
catch (e)
{
if (e !== BreakException) throw e;
}
Copy Code
Use Array#some
:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
Copy Code This works because some
returns true
as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.
We can use every
method:
[1,2,3].every(function(el) {
return !(el === 1);
});
Copy Code For old browser support this below code:
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;
};
}
Copy Code
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;
}
}
Copy Code
Consider to use jquery's each method, since it allows to return false inside callback function :
$.each(function(e, i) {
if (i % 2) return false;
console.log(e)
})
Copy Code Lodash libraries provides
takeWhile
method that can be bound with map/reduce/fold etc:
var users = [
{ 'user': 'wiki', 'active': false },
{ 'user': 'techy', 'active': false },
{ 'user': 'wikitechy', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['wiki', 'techy']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'wiki', 'active': false });
// => objects for ['wiki']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['wiki', 'techy']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
Copy Code
Here we can use Array.prototype.find
method:
[1, 2, 3].find(function(el) {
return el === 2;
}); // returns 2
Copy Code