Tablica JavaScript dla każdego()
Przykład 1
Wywołuje funkcję dla każdego elementu w owocach:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Definicja i użycie
Metoda forEach()
wywołuje funkcję dla każdego elementu w tablicy.
Metoda forEach()
nie jest wykonywana dla pustych elementów.
Składnia
array.forEach(function(currentValue, index, arr), thisValue)
Parametry
function() | Required. A function to run for each array element. |
currentValue | Required. The value of the current element. |
index | Optional. The index of the current element. |
arr | Optional. The array of the current element. |
thisValue | Optional. Default undefined .A value passed to the function as its this value. |
Wartość zwrotu
nieokreślony |
Obsługa przeglądarki
forEach()
to funkcja ECMAScript5 (ES5).
ES5 (JavaScript 2009) w pełni obsługiwany we wszystkich przeglądarkach:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Więcej przykładów
Oblicz sumę:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Pomnóż każdy element:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}