Looping over arrays using functions is increasingly common, especially in
certain libraries. Modern browsers support the forEach() method, but
you can also build your own.
function arrayForEach(array, loopFunc) {
// If the browser support forEach, use it because
// it will be faster
if ("forEach" in array) {
return array.forEach(loopFunc);
// Otherwise, loop over the array and pass in
// the array values to the loop function
} else {
for (var i = 0, l = array.length; i < l; i++) {
loopFunc(array[i], i, array);
}
return array;
}
}
function doSomeMath(num) {
console.log(num * 10 - 5);
}
arrayForEach([1,2,3], doSomeMath);
5
15
25
certain libraries. Modern browsers support the forEach() method, but
you can also build your own.
function arrayForEach(array, loopFunc) {
// If the browser support forEach, use it because
// it will be faster
if ("forEach" in array) {
return array.forEach(loopFunc);
// Otherwise, loop over the array and pass in
// the array values to the loop function
} else {
for (var i = 0, l = array.length; i < l; i++) {
loopFunc(array[i], i, array);
}
return array;
}
}
function doSomeMath(num) {
console.log(num * 10 - 5);
}
arrayForEach([1,2,3], doSomeMath);
5
15
25