Matriz de JavaScript para cada uno ()
Ejemplo 1
Llama a una función para cada elemento en las frutas:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Definición y uso
El forEach()
método llama a una función para cada elemento de una matriz.
El forEach()
método no se ejecuta para elementos vacíos.
Sintaxis
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 devuelto
indefinido |
Compatibilidad con navegador
forEach()
es una característica de ECMAScript5 (ES5).
ES5 (JavaScript 2009) totalmente compatible con todos los navegadores:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Más ejemplos
Calcular la suma:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Multiplica cada elemento:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}