reduce() 方法是 javascript 中一个强大的数组方法,用于迭代数组并将其减少为单个值。该方法用途广泛,可以处理数字求和、展平数组、创建对象等操作。
减少()的语法
1
array.reduce(callback, initialvalue);
reduce() 如何逐步工作
从初始值开始,如果没有提供初始值,则从数组的第一个元素开始。 将累加器和 currentvalue 传递给回调函数。 使用回调的返回值更新累加器。 重复,直到处理完所有元素。 返回最终的累计值。示例 1:计算数组的总计(现实生活:购物车)
假设您有一个购物车,并且您想要计算商品的总价。
1
2
3
4
5
6
7
8
9
const cart = [
{ item: "laptop", price: 1200 },
{ item: "phone", price: 800 },
{ item: "headphones", price: 150 }
];
const totalprice = cart.reduce((acc, curr) => acc + curr.price, 0);
console.log(`total price: $${totalprice}`); // total price: $2150
示例 2:按类别对物品进行分组(现实生活:组织库存)
您想要按类别对项目进行分组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const inventory = [
{ name: "apple", category: "fruits" },
{ name: "carrot", category: "vegetables" },
{ name: "banana", category: "fruits" },
{ name: "spinach", category: "vegetables" }
];
const groupeditems = inventory.reduce((acc, curr) => {
if (!acc[curr.category]) {
acc[curr.category] = [];
}
acc[curr.category].push(curr.name);
return acc;
}, {});
console.log(groupeditems);
/*
{
fruits: [apple, banana],
vegetables: [carrot, spinach]
}
*/
示例 3:展平嵌套数组(现实生活:合并部门数据)
您以嵌套数组的形式接收来自不同部门的数据,需要将它们合并为一个。
1
2
3
4
5
6
7
8
9
const departmentdata = [
["john", "doe"],
["jane", "smith"],
["emily", "davis"]
];
const flatteneddata = departmentdata.reduce((acc, curr) => acc.concat(curr), []);
console.log(flatteneddata); // [john, doe, jane, smith, emily, davis]
示例 4:计算出现次数(现实生活:分析)
您有一系列网站页面浏览量,并且想要计算每个页面的访问次数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const pageviews = ["home", "about", "home", "contact", "home", "about"];
const viewcounts = pageviews.reduce((acc, page) => {
acc[page] = (acc[page] || 0) + 1;
return acc;
}, {});
console.log(viewcounts);
/*
{
home: 3,
about: 2,
contact: 1
}
*/
示例 5:使用reduce() 实现自定义映射
reduce()方法可以模仿map()的功能。
1
2
3
4
5
6
7
8
const numbers = [1, 2, 3, 4];
const doubled = numbers.reduce((acc, curr) => {
acc.push(curr * 2);
return acc;
}, []);
console.log(doubled); // [2, 4, 6, 8]
示例 6:查找最大值(现实生活中:查找销量最高的产品)
您想要从数据集中找到最高的销售额。
1
2
3
4
5
const sales = [500, 1200, 300, 800];
const highestsale = sales.reduce((max, curr) => (curr > max ? curr : max), 0);
console.log(`highest sale: $${highestsale}`); // highest sale: $1200
示例 7:转换数据(现实生活:api 数据转换)
您收到一个用户数据数组,需要将其转换为由用户 id 键入的对象。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const users = [
{ id: 1, name: "John Doe" },
{ id: 2, name: "Jane Smith" },
{ id: 3, name: "Emily Davis" }
];
const usersById = users.reduce((acc, user) => {
acc[user.id] = user;
return acc;
}, {});
console.log(usersById);
/*
{
1: { id: 1, name: John Doe },
2: { id: 2, name: Jane Smith },
3: { id: 3, name: Emily Davis }
}
*/
提示和最佳实践
使用initialvalue:始终提供一个initialvalue,以避免处理空数组时出现意外行为。 保持简单:编写简洁明了的reducer函数。 不可变更新:使用对象或数组时,避免直接在减速器内改变它们。结论
reduce() 方法非常通用,可以适应各种任务,从求和到转换数据结构。使用这些现实生活中的示例进行练习,以加深您的理解并释放您的 javascript 项目中的 reduce() 的全部潜力。
以上就是JavaScript `reduce()` 方法综合指南与现实生活中的例子的详细内容,更多请关注php中文网其它相关文章!