我是 JavaScript 新手,正在阅读有关映射、过滤器和归约等高阶函数的内容。 为了实际操作,我尝试了以下示例: 假设购物车中有一些商品,使用reduce计算商品的总成本。
var products = [{
"id": 100,
"name": "Dell laptop",
"category": "Laptop",
"price": 40000
}, {
"id": 100,
"name": "LG Mobile",
"category": "Mobile",
"price": 20000
}, {
"id": 100,
"name": "HP laptop",
"category": "Laptop",
"price": 60000
}, {
"id": 100,
"name": "Samsung Mobile",
"category": "Mobile",
"price": 25000
}];
var total = 0;
var result = products.reduce(function (total, product) {
return total + parseInt(product.price);
});
console.log("Total cost of cart : " + result);
上述代码的输出如下所示:
Total cost of cart : [object Object]200006000025000
现在我修改了上面的代码并添加了 map ,它们工作正常:
var result = products.map(function (product) {
return product.price;
}).reduce(function (total, price) {
return total + price;
});
我得到了正确的结果。
现在我的问题是为什么我不能单独使用reduce API?
最佳答案
是的,可以。不需要两次 reduce
调用。只需将初始值 0
作为最后一个参数传递给 reduce
。
var total = products.reduce(function(prev, curr) {
return prev + curr.price;
}, 0);
// ^^ Initial value
var products = [{
"id": 100,
"name": "Dell laptop",
"category": "Laptop",
"price": 40000
}, {
"id": 100,
"name": "LG Mobile",
"category": "Mobile",
"price": 20000
}, {
"id": 100,
"name": "HP laptop",
"category": "Laptop",
"price": 60000
}, {
"id": 100,
"name": "Samsung Mobile",
"category": "Mobile",
"price": 25000
}];
var total = products.reduce(function(prev, curr) {
return prev + curr.price;
}, 0);
document.body.innerHTML = total;
关于javascript - 我们可以使用参数对象集合而不是原始数据来调用 JavaScript collection.reduce() 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37201267/