所以我有一个赋值,我只能在某些行中添加代码,但是我需要获取数组的总和然后返回它。我使用了reduce,但我不知道在函数内部如何将它添加到变量total中,并且我不允许更改total的值。
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// code below
shoppingCart.reduce((total, amount) => total + amount);
// code above
return total;
}
getTotalCost(shoppingCart);
答案 0 :(得分:1)
看起来,您的代码存在多个问题:
您需要转让或只返回Array#reduce
的值。
我建议也使用起始值,因为空数组使用reduce
会引发错误。
在函数getTotalCost
内部,您需要使用移交的数组prices
,而不是硬编码的shoppingCart
数组。
function getTotalCost(prices) {
return prices.reduce((total, amount) => total + amount, 0);
}
console.log(getTotalCost([20, 15]));
console.log(getTotalCost([]));
答案 1 :(得分:0)
最简单的是
shoppingCart.forEach(price => total += price)
答案 2 :(得分:-1)
total
函数中的 reduce
无法访问在(total
)之外声明的let total = 0
变量,它具有它自己的范围并且仅限于这个回调数组函数,因此,一旦reduce
函数返回输出,它的值就不会被反映出来。
<强>演示强>
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
//this line prints 20 but that value is not reflected in total declared outside
shoppingCart.reduce((total, amount) => (console.log(total), total + amount));
return total;
}
console.log(getTotalCost(shoppingCart));
&#13;
只需将reduce
的返回值保存到total
total = shoppingCart.reduce((total, amount) => total + amount);
<强>演示强>
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// code below
total = shoppingCart.reduce((total, amount) => total + amount);
// code above
return total;
}
console.log(getTotalCost(shoppingCart));
&#13;
此外,您可以在reduce
total = shoppingCart.length && shoppingCart.reduce((total, amount) => total + amount);