
reduce() 方法是 javascript 中一个强大的数组方法,用于迭代数组并将其减少为单个值。该方法用途广泛,可以处理数字求和、展平数组、创建对象等操作。
array.reduce(callback, initialvalue);
假设您有一个购物车,并且您想要计算商品的总价。
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
您想要按类别对项目进行分组。
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']
}
*/
您以嵌套数组的形式接收来自不同部门的数据,需要将它们合并为一个。
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']
您有一系列网站页面浏览量,并且想要计算每个页面的访问次数。
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
}
*/
reduce()方法可以模仿map()的功能。
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]
您想要从数据集中找到最高的销售额。
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
您收到一个用户数据数组,需要将其转换为由用户 id 键入的对象。
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' }
}
*/
reduce() 方法非常通用,可以适应各种任务,从求和到转换数据结构。使用这些现实生活中的示例进行练习,以加深您的理解并释放您的 javascript 项目中的 reduce() 的全部潜力。
以上就是JavaScript `reduce()` 方法综合指南与现实生活中的例子的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号