Matrice JavaScript forEach()
Esempio 1
Chiama una funzione per ogni elemento in fruits:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Definizione e utilizzo
Il forEach()
metodo chiama una funzione per ogni elemento in una matrice.
Il forEach()
metodo non viene eseguito per elementi vuoti.
Sintassi
array.forEach(function(currentValue, index, arr), thisValue)
Parametri
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. |
Valore di ritorno
non definito |
Supporto browser
forEach()
è una funzione ECMAScript5 (ES5).
ES5 (JavaScript 2009) completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Altri esempi
Calcola la somma:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Moltiplica ogni elemento:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}