Freigeben über


Array.forEach Function

Calls a specified function for each element of an Array object. This function is static and can be invoked without creating an instance of the object.

Array.forEach(array, method, instance);

Arguments

Term

Definition

array

The Array object to enumerate.

method

The function to call for each element in the array.

instance

The context for calling method.

Remarks

Use the forEach function to invoke a specified function for each element in an array.

The function specified by the method parameter must accept the following arguments in the following order: element, index, and array. The element argument is the array element that the function will take action on. The index argument is the index of element, and the array argument is the array that contains element.

Note

In all browsers except Mozilla Firefox, the forEach function skips elements in the array that have a value of undefined. The function skips unassigned elements in all browsers.

Example

The following example shows how to use the forEach function to append a character between each existing element of an array.

var a = ['a', 'b', 'c', 'd'];
a[5] = 'e';
var result = '';

function appendToString(element, index, array) {
    // "this" is the context parameter, i.e. '|'.
    result += element + this + index + ',';
}
Array.forEach(a, appendToString, '|');
// View the results: a|0,b|1,c|2,d|3,e|5,
alert(result);

See Also

Reference

Array Object

Array Type Extensions

Other Resources

Language Reference