我是Java语言的超级新手,目前是一个训练营的学生,完全陷入了这个问题...
“使用shoppingCart变量,创建一个采用shoppingCart变量并返回两项总费用作为总变量的函数。”
我得到的代码是:
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// code below
// code above
return total;
}
getTotalCost(shoppingCart);
我知道我必须完成功能并遍历shoppingCart中的数组,但是在弄清楚如何添加数组编号以使其总和时遇到很多麻烦。救命。谢谢!
答案 0 :(得分:2)
答案 1 :(得分:0)
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// Loop through each element of the array 'prices'
for (var i = 0; i < prices.length; i++){
// Add individual item to total sum
total += prices[i];
}
return total;
}
console.log(getTotalCost(shoppingCart));
答案 2 :(得分:0)
您可以使用forEach函数迭代价格数组。
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// forEach works with arrays.
prices.forEach(function(price){
// Parse your value into an integer to prevent string concatenations.
total = total + parseInt(price);
});
return total;
}
let total = getTotalCost(shoppingCart);
console.log('Your shopping cart total is:', total);