我刚学了javascript。为什么返回值是NaN?
var arr = [
{ name: "A", quantity: 1, price: 20 },
{ name: "B", quantity: 2, price: 40 },
{ name: "C", quantity: 3, price: 60 },
{ name: "D", quantity: 4, price: 80 }
];
var test = arr.reduce(function(item1, item2){
return (item1.quantity * item1.price) + (item2.quantity * item2.price);
});
console.log(test);Run Code Online (Sandbox Code Playgroud)
从Array.reduce()文档:
reducer 函数有四个参数:
- 蓄能器 (acc)
- 当前值 (cur)
- 当前索引 (idx)
- 源数组 (src)
您的 reducer 函数的返回值被分配给累加器,其值在整个数组的每次迭代中都会被记住,并最终成为最终的单个结果值。
所以,我相信你想这样做:
var arr = [
{ name: "A", quantity: 1, price: 20 },
{ name: "B", quantity: 2, price: 40 },
{ name: "C", quantity: 3, price: 60 },
{ name: "D", quantity: 4, price: 80 }
];
var test = arr.reduce(function(acc, curr)
{
return acc + (curr.quantity * curr.price);
}, 0);
console.log(test);Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}Run Code Online (Sandbox Code Playgroud)
请注意,明确定义累加器的初始值总是好的(0在这种特殊情况下)。即使它是可选的,也不适用于这种情况:
initialValue可选:用作回调第一次调用的第一个参数的值。如果未提供初始值,则将使用数组中的第一个元素。在没有初始值的空数组上调用 reduce() 是一个错误。
为什么你得到 NaN?
由于您没有明确定义累加器的初始值,它将是数组中的第一个对象:
{name: "A", quantity: 1, price: 20}
Run Code Online (Sandbox Code Playgroud)
现在, 的第一次迭代reduce()将起作用,因为累加器(item1在您的示例中命名)是一个对象并且具有属性quantity和price。更重要的是,此迭代将返回1 * 20 + 2 * 40 = 100,这将是累加器 ( item1)的新值。现在, 的第二次和以后的迭代reduce()不会像您期望的那样工作,因为累加器的新值(在第一次迭代之后)不是一个对象并且不会具有属性quantity和price。因此,最新一期将导致获得NaN最终价值。