Я супер новичок в Javascript и в настоящее время студент в bootcamp, и я полностью застрял в этом вопросе...
"Используя переменную shoppingCart, создайте функцию, которая принимает переменную shoppingCart и возвращает общую стоимость обоих элементов в качестве общей переменной".
Код, который я даю:
var shoppingCart = [20, 15];
function getTotalCost(prices){
let total = 0;
// code below
// code above
return total;
}
getTotalCost(shoppingCart);
Я знаю, что мне нужно выполнить функцию и перебрать массив в shoppingCart, но у меня много проблем, когда мы выясняем, как добавлять номера массивов, чтобы они отображались как сумма. Я бы ДЕЙСТВИТЕЛЬНО оценил любую помощь. Спасибо!
Вы можете легко достичь этого путем цикла в javascript, аналогично
var shoppingCart = [20, 15];
function getTotalCost(shoppingCart){
let total = 0;
for(var i in shoppingCart) { total += shoppingCart[i]; }
return total;
}
console.log(getTotalCost(shoppingCart));
Вы можете просто перебрать свой массив цен с помощью функции 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);
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));