Matriz JavaScript para Cada()
Exemplo 1
Chama uma função para cada elemento em frutas:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Definição e uso
O forEach()
método chama uma função para cada elemento em uma matriz.
O forEach()
método não é executado para elementos vazios.
Sintaxe
array.forEach(function(currentValue, index, arr), thisValue)
Parâmetros
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. |
Valor de retorno
Indefinido |
Suporte ao navegador
forEach()
é um recurso ECMAScript5 (ES5).
ES5 (JavaScript 2009) totalmente suportado em todos os navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Mais exemplos
Calcule a soma:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Multiplique cada elemento:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}