javascript - 我们可以使用参数对象集合而不是原始数据来调用 JavaScript collection.reduce() 方法吗?

标签 javascript

我是 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/

相关文章:

javascript - 我是否在 JavaScript 中正确嵌套了这些 if/else if 语句?

javascript - 使复选框看起来像按钮 CSS

javascript - Protractor - beforeEach 中的异步任务

javascript - 获取无效的形式参数

javascript - 库中的 React Router 问题 - 使用 <Router> 之外的元素

javascript - 是否可以使用 jQuery/javascript 每隔 x 像素重复放置一个 DIV

javascript - 我如何使用带有持续时间和缓动的 slideToggle()?

javascript - Chrome DIV 未完全绘制

javascript - 控制台中的 jQuery 无法正常工作

javascript - 如何解析键并在javascript中获取它的值