js reduce方法
在JavaScript中,reduce()方法是数组对象自带的一个高阶函数,用来对数组中的每个元素执行指定的函数,并将结果累积。
reduce()方法的语法
array.reduce(callback[, initialValue])
callback
:用来处理数组中每个元素的函数,包含四个参数:accumulator
(累加器)、currentValue
(当前元素值)、currentIndex
(当前元素索引)和array
(数组本身)。initialValue
(可选):可作为计算的初始值,如果不提供该参数,将使用数组的第一个元素作为初始值。
reduce()方法的用法
示例1:计算数组元素之和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出 15
示例2:将数组中的数字转为字符串连接在一起
const numbers = [1, 2, 3, 4, 5];
const result = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue.toString();
}, "");
console.log(result); // 输出 "12345"
示例3:将二维数组扁平化为一维数组
const arr = [[1, 2], [3, 4], [5, 6]];
const flattened = arr.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(flattened); // 输出 [1, 2, 3, 4, 5, 6]
示例4:将数组中的对象属性值相加
const data = [
{ value: 1 },
{ value: 2 },
{ value: 3 }
];
const total = data.reduce((accumulator, currentValue) => {
return accumulator + currentValue.value;
}, 0);
console.log(total); // 输出 6
reduce()方法的注意事项
- 如果不提供
initialValue
,则accumulator
初始值为数组的第一个元素,currentValue
从数组第二个元素开始。 reduce()
方法不会改变原数组。- 当数组为空且无初始值时,会抛出
TypeError
异常。
使用reduce()
方法可以简洁地实现对数组元素的累积处理,同时也可以有效地减少冗余的代码量,提高代码的可读性。