JavaScript配列reduce()
例
配列内のすべての数値を減算します。
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
すべての数値を丸めて、合計を表示します。
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
function getSum(total, num) {
return total + Math.round(num);
}
定義と使用法
このreduce()
メソッドは、配列要素のレデューサー関数を実行します。
このreduce()
メソッドは、関数の累積結果という単一の値を返します。
このreduce()
メソッドは、空の配列要素に対して関数を実行しません。
このreduce()
メソッドは元の配列を変更しません。
関連項目:
構文
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
パラメーター
Parameter | Description | ||||||||
function() | Required. A function to be run for each element in the array. |
||||||||
Reducer function parameters:
| |||||||||
initialValue | Optional. A value to be passed to the function as the initial value. |
戻り値
コールバック関数の最後の呼び出しからの累積結果。 |
ブラウザのサポート
reduce()
ECMAScript5(ES5)機能です。
ES5(JavaScript 2009)は、すべてのブラウザーで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |