Pole JavaScript forEach()
Příklad 1
Volá funkci pro každý prvek v ovoci:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Definice a použití
Metoda forEach()
volá funkci pro každý prvek v poli.
Metoda forEach()
se neprovádí pro prázdné prvky.
Syntax
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. |
Návratová hodnota
nedefinováno |
Podpora prohlížeče
forEach()
je funkce ECMAScript5 (ES5).
ES5 (JavaScript 2009) plně podporován ve všech prohlížečích:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
Další příklady
Vypočítejte součet:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Vynásobte každý prvek:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}