【发布时间】:2020-07-19 02:07:04
【问题描述】:
有人可以向我解释一下这些例子之间的区别吗?
这是原始代码。
const items = [
{ name: "Bike", price: 100 },
{ name: "TV", price: 200 },
{ name: "Album", price: 10 },
{ name: "Book", price: 5 },
{ name: "Phone", price: 500 },
{ name: "Computer", price: 1000 },
{ name: "Keyboard", price: 25 },
];
const total = items.reduce((total, amount) => {
return total + amount.price;
});
console.log("total", total);
以上返回 total [object Object]200105500100025
const total = items.reduce((total, amount) => {
return total + amount.price;
}, 0);
这段代码返回total 1840,这是我一直在寻找的,但为什么会有 ,0);最后改变这个结果?它是否将价格值更改为“数字”而不是像上面那样的“对象”或“字符串”?
我注意到 YouTube 上的一些教程说因为它是一个箭头函数,所以我不需要输入“return”并使代码看起来像:
const total = items.reduce((total, amount) => {total + amount.price}, 0);
但这会给我返回total undefined的结果
有return 和没有有什么区别?
【问题讨论】:
-
阅读arrow functions 和reduce() 的文档应该可以帮助您解决这两个问题
标签: javascript string numbers concatenation reduce