Break Arry iterator in EVERY way in JavaScript
For loop is good for old time in before javascript, but now we use the forEach most time. it is useful for every developers. But the problem is, how we break it like FOR loop does?
in my way,
var arr = ["a", "b", "c", "d", "e", "f"];
var executeFlag = true;arr.forEach(function(val, idx) {
if ( ! executeFlag) {
return;
}if (idx === 3) {
executeFlag = false;
}console.log(idx);
});
</pre>it works well, and it can solve problem. But now you can try this EVERY in Array.
Every seems a new spec in Array in W3C. However it can solve this kind problem easily.
var passed = ["a", "b", "c", "d", "e", "f"].every(function (element, index, array) {
var flag = (index < 3);
if ( ! flag) {
return flag;
}console.log(element);
return true;
});
</pre>it is rock, i love EVERY method so much, thanks every browser support except IE. Also it work well in Node.js.
Written by Caesar Chi
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside