You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
One of the major problem with the standard Array.forEach method is that you cannot break it. I have modified your code to support such feature with only a few minor changes and I think it would be most useful to solve many use cases:
var forEach = function (collection, callback, scope) {
var result = false;
if (Object.prototype.toString.call(collection) === '[object Object]') {
for (var prop in collection) {
if (Object.prototype.hasOwnProperty.call(collection, prop)) {
result = callback.call(scope, collection[prop], prop, collection);
if (result !== undefined) {
break;
}
}
}
} else {
for (var i = 0, len = collection.length; i < len; i++) {
result = callback.call(scope, collection[i], i, collection);
if (result !== undefined) {
break;
}
}
}
return result;
};
Hey Nicolas! Yeah, I love the idea of doing this, but it would go against the spec of forEach, and if you need to break, you'll likely want to use some or every rather than forEach to use the right method for the task.
It all depends on what is your definition of forEach. I personaly tihnk that the JavaScript definition is quite limited. You can check PHP's foreach which is quite more flexible. In any case I'm tired of the boilerplate required in JavaScript, I created my own 20 lines repo for those who also feel the pain :) https://github.com/nbouvrette/forEach
One of the major problem with the standard Array.forEach method is that you cannot break it. I have modified your code to support such feature with only a few minor changes and I think it would be most useful to solve many use cases:
For example you could use it like this:
The result would loop on 1, then ,2 and stop there returning the output.
The text was updated successfully, but these errors were encountered: