外贸网站推广有哪些,简约创意情人节海报设计,wordpress 外链图片缩略图,邯郸超速云_网站建设Array.prototype.reduce 是 JavaScript 数组方法之一#xff0c;用于累积数组的各个值#xff0c;将其简化为单个值。下面是一些基础用法和一些可能被认为奇怪或不太常见的用法#xff1a;
基础用法#xff1a;
数组求和#xff1a;
const numbers [1, 2, 3, 4, 5];
c…Array.prototype.reduce 是 JavaScript 数组方法之一用于累积数组的各个值将其简化为单个值。下面是一些基础用法和一些可能被认为奇怪或不太常见的用法
基础用法
数组求和
const numbers [1, 2, 3, 4, 5];
const sum numbers.reduce((acc, curr) acc curr, 0);
console.log(sum); // 输出 15查找最大值
const values [10, 30, 50, 20, 40];
const max values.reduce((acc, curr) Math.max(acc, curr), -Infinity);
console.log(max); // 输出 50数组去重
const duplicates [1, 2, 2, 3, 4, 4, 5];
const uniqueValues duplicates.reduce((acc, curr) {if (!acc.includes(curr)) {acc.push(curr);}return acc;
}, []);
console.log(uniqueValues); // 输出 [1, 2, 3, 4, 5]奇怪的用法
数组平铺
const nestedArray [[1, 2], [3, 4], [5, 6]];
const flatArray nestedArray.reduce((acc, curr) acc.concat(curr), []);
console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6]对象数组转对象
const people [{ id: 1, name: John },{ id: 2, name: Jane },{ id: 3, name: Doe },
];
const peopleObject people.reduce((acc, person) {acc[person.id] person.name;return acc;
}, {});
console.log(peopleObject); // 输出 {1: John, 2: Jane, 3: Doe}条件统计
const numbers [1, 2, 3, 4, 5];
const countEvenOdd numbers.reduce((acc, curr) {curr % 2 0 ? acc.even : acc.odd;return acc;},{ even: 0, odd: 0 }
);
console.log(countEvenOdd); // 输出 {even: 2, odd: 3}这些示例展示了 reduce 的一些基础和创造性的用法。由于 reduce 具有强大的灵活性它可以应用于许多场景。