I'm trying to understand if it is possible to use an array iterator (like .forEach()) to complete the same functionality as a for loop.
I am trying to understand javascript event listeners and have written some basic code to help me learn
I have multiple div's with a class name of 'button'.
I have the functionality I want to achieve working using a for loop but have not been able to work out how to do the same with an iterator. IS it possible??
// Can I use an Array Iterator to do the same operation here
for (var i = 0; i < button.length; i++) {
addEvent(button[i]);
}
See a JSFiddle of all my code here
I have tried using the .forEach() iterator but couldn't work out how to grab the array index in the forEach() iterator as I need to define which button to run the addEvent function on.
button
, in code you only posted a link to, is an HTMLCollection, so there isn't much you can do with it "natively"
However, using Array.from you can "convert" it to an array, and then use the Array#forEach method - so, your code would be
Array.from(button).forEach(function(btn) {
addEvent(btn);
});
or, even better
Array.from(button).forEach(addEvent);
If you are dealing with Internet Exploder, you'll need the Polyfill for Array.from
If you need to deal with Internet Exploder prior to version 9, you'll need the Polyfill for Array.prototype.forEach
The MDN documentation I linked to has Polyfills for both