A simple forEach() implementation for Arrays, Objects and NodeLists that takes away repetitive object lookups and array notations. Pass in any type and it'll iterate and pass back all the necessary goods such as index, element, property, value and object. The syntax is a simple function wrapper.
You can loop over an Array or NodeList using a standard for loop, however, NodeLists cannot be used in conjunction with the newer ECMAScript 5 Array.prototype.forEach. This script takes care of that in the same way it loops over an Array, you'll get the same stuff passed back:
// Array:
forEach(['A', 'B', 'C', 'D'], function (value, index) {
console.log(value); // A, B, C, D
console.log(index); // 0, 1, 2, 3
});
// NodeList:
forEach(document.querySelectorAll('div'), function (value, index) {
console.log(value); // <div>, <div>, <div>...
console.log(index); // 0, 1, 2...
});Object iteration is usually done via a for in loop, we can wrap this up by passing back values which makes our loops cleaner and easier to manage:
// Object:
forEach({ name: 'Todd', location: 'UK' }, function (value, prop, obj) {
console.log(value); // Todd, UK
console.log(prop); // name, location
console.log(obj); // { name: 'Todd', location: 'UK' }, { name: 'Todd', location: 'UK' }
});Type: Array|Object|NodeList
Collection of items to iterate, could be an Array, Object or NodeList.
Type: Function
Callback function for each iteration.
Type: Array|Object|NodeList Default: null
Object/NodeList/Array that forEach is iterating over, to use as the this value when executing callback.
I used it to iterate through objects, works great!