// 示例代码:使用 reduce 计算数组中所有元素的总和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出: 15
// 解释说明:
// reduce 方法会遍历数组中的每一个元素,并将当前元素传递给回调函数。
// 回调函数接收两个参数:accumulator(累加器)和 currentValue(当前值)。
// 累加器保存了上一次回调函数返回的结果,初始值为 0。
// 每次回调函数执行时,将累加器与当前值相加,最终返回累加后的总和。
// 示例代码:使用 reduce 将数组中的对象按某个属性进行分组
const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 },
{ name: 'David', age: 30 }
];
const groupedByAge = people.reduce((accumulator, person) => {
const age = person.age;
if (!accumulator[age]) {
accumulator[age] = [];
}
accumulator[age].push(person);
return accumulator;
}, {});
console.log(groupedByAge);
// 输出:
// {
// 25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }],
// 30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }]
// }
// 解释说明:
// 这里我们使用 reduce 方法将数组中的对象按年龄属性进行分组。
// 初始值是一个空对象 {},每次迭代时检查当前年龄是否已经存在于累加器中,
// 如果不存在则创建一个空数组,然后将当前对象添加到对应的数组中。
// 最终返回一个以年龄为键的对象,每个键对应一个包含相同年龄对象的数组。
上一篇:js confirm 弹窗
下一篇:js new file()
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站