
reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce()方法为每个数组索引执行一次回调函数。
函数的返回值存储在累加器(result)中。
语法:
array.reduce(callback, initialValue)
var nums = [10, 20, 30, 40, 50];
var sum = nums.reduce(getTotal);
function getTotal(x, y) {
return (x + y);
}测试看看‹/›浏览器兼容性
表格中的数字指定了完全支持reduce()方法的第一个浏览器版本:
| Method | ![]() | ![]() | ![]() | ![]() | ![]() |
| reduce() | 是 | 3 | 10.5 | 4 | 9 |
参数值
| 参数 | 描述 |
|---|---|
| callback | 为数组中的每个元素运行的函数。 函数参数:
|
| initialValue | (可选)用作首次调用回调的第一个参数的值。 如果未提供初始值,则将使用数组中的第一个元素。 |
技术细节
| 返回值: | 减少产生的值 |
|---|---|
| JavaScript版本: | ECMAScript 5 |
更多实例
本示例删除数组中的重复项:
var nums = [10, 20, 10, 20, 13, 5, 4, 5, 13, 4, 4, 4, 4];
let result = nums.sort().reduce((accumulator, current) => {
const length = accumulator.length;
if (length === 0 || accumulator[length - 1] !== current) {
accumulator.push(current);
}
return accumulator;
}, []);
function myFunc() {
document.getElementById("result").innerHTML = result;
}测试看看‹/›reduce()和reduceRight()之间的区别:
var arr = ['1', '2', '3', '4', '5'];
function funcReduce() {
var val = arr.reduce(function(x, y) {return x + y;});
document.getElementById("result").innerHTML = val;
}
function funcReduceRight() {
var val = arr.reduceRight(function(x, y) {return x + y;});
document.getElementById("result").innerHTML = val;
}测试看看‹/›HTML DOM addEventListener() 方法 JavaScript NEGATIVE_INFINITY 属性




