Shorthand method:
var myArray = Array('apple', 'banana', 'carrot');
You can use a standard for-loop:
var myArray = Array('apple', 'banana', 'carrot');
for (var i = 0, j = myArray.length; i < j; i++) {
console.log(myArray[i]);
}
or you could use a higher-order function (see below).
var myArray = Array('apple', 'banana', 'carrot');
function showFruit(fruit) {
console.log(fruit);
}
myArray.forEach(showFruit);
Do not use the for each ($item in $array) {... construct to loop over an array.
Scroll down to the Iteration Methods section.
In mathematics and computer science, a higher-order function is a function that does at least one of the following:
From a practical perspective, Javascript’s Array object has the following prototype functions that are higher-order (Mozilla calls these Iteration Methods).
Uses an accumulator to get a single value.
var myArray = Array(
{age: 15, name: 'Samantha'},
{age: 46, name: 'Craig'},
{age: 52, name: 'Nancy'},
{age: 8, name: 'Alison'},
{age: 77, name: 'Betty'}
);
function sumAge(previousValue, currentValue, index, array) {
//Because currentValue is an object, you need to return an object.
return {
age: previousValue.age + currentValue.age
};
}
var ageSummation = myArray.reduce(sumAge);
console.log('Average age is ' + (ageSummation.age / myArray.length)); //39.6