JavaScript 数组高级方法:map、filter、reduce 实践
数组方法是函数式编程的基石,可替代循环。
1. map(转换)
const nums = [1, 2, 3, 4];
const doubled = nums.map(x => x * 2); // [2,4,6,8]2. filter(过滤)
const evens = nums.filter(x => x % 2 === 0); // [2,4]3. reduce(累积)
const sum = nums.reduce((acc, cur) => acc + cur, 0); // 10
// 使用 reduce 实现分组
const items = [{type: 'fruit', name: 'apple'}, {type: 'fruit', name: 'banana'}, {type: 'veg', name: 'carrot'}];
const grouped = items.reduce((acc, item) => {
acc[item.type] = acc[item.type] || [];
acc[item.type].push(item.name);
return acc;
}, {});4. 链式调用
const result = nums
.filter(x => x % 2 === 0)
.map(x => x * 10)
.reduce((acc, cur) => acc + cur, 0); // 60熟练使用这些方法可写出更简洁、可读性更强的代码。
