Skip to content

Instantly share code, notes, and snippets.

@eikeco
Created September 22, 2016 09:41
Show Gist options
  • Save eikeco/42b4a18af5f9a0e5b54f311b4689d0ba to your computer and use it in GitHub Desktop.
Save eikeco/42b4a18af5f9a0e5b54f311b4689d0ba to your computer and use it in GitHub Desktop.
A better forEach method than the [].forEach.call(NodeList) hack
// forEach method, could be shipped as part of an Object Literal/Module
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]); // passes back stuff we need
}
};
// Usage:
// optionally change the scope as final parameter too, like ECMA5
var myNodeList = document.querySelectorAll('li');
forEach(myNodeList, function (index, value) {
console.log(index, value); // passes index + value back!
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment