Array.prototype.forEach()

.forEach() executes the callback function on each item of the array once.

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);

How to use:

  1. Create a callback function
    function logArrayElements(element, index, array) {
      console.log('a[' + index + '] = ' + element);
    }
  2. Apply callback function to .forEach() method
    [2, 5, , 9].forEach(logArrayElements);
    
    // a[0] = 2
    // a[1] = 5
    // a[3] = 9

* This can be combined into one step if the callback function is simple.

 

Advertisements
Array.prototype.forEach()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s