JavaScript配列forEach()
例1
果物の各要素の関数を呼び出します。
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
定義と使用法
このforEach()
メソッドは、配列内の要素ごとに関数を呼び出します。
このforEach()
メソッドは、空の要素に対しては実行されません。
構文
array.forEach(function(currentValue, index, arr), thisValue)
パラメーター
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. |
戻り値
未定義 |
ブラウザのサポート
forEach()
ECMAScript5(ES5)機能です。
ES5(JavaScript 2009)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |
その他の例
合計を計算します。
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
各要素を乗算します。
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}