Skip to content

forEach

Mike Byrne edited this page Jan 25, 2022 · 4 revisions

🚨Deprecation notice🚨

Q3 of 2019 this will be removed from a17-helpers. Consider using Array.prototype.forEach and NodeList.prototype.forEach instead. BP v5.0.5+ has a polyfill for NodeList.prototype.forEach.

description

Run a function on each item of an array. You may way to consider the native Array.forEach but remember, if using HTML node collections to convert the collection to an Array.

requires

  • nothing

parameters

  • array - required - array to loop over
  • callback - required - function to run on each item in the array
  • scope - optional - scope of this inside the callback function

returns

  • index and item for each item in the array

example usage:

forEach(document.querySelectorAll('a[rel=external'], function(index, link) {
  link.setAttribute('target','_blank');
});

No scope:

var arr = ['one','two','three'];
var func = function(i, item) {
  console.log(this, i, item);
}

forEach(arr, func);

Which will log out:

window 0 "one"
window 1 "two"
window 2 "three"

With scope:

var arr = ['one','two','three'];
var scope = document.createElement('span');
var func = function(i, item) {
  console.log(this, i, item);
}

forEach(arr, func, scope);

Which will log out:

<span></span> 0 "one"
<span></span> 1 "two"
<span></span> 2 "three"