Function that console.log's the total of all items together

时间:2017-08-04 12:38:50

标签: javascript arrays

I want to create a function called totalPriceCheck that console.log's the total of all shoppingCart items together.

    var shoppingCart = [];

    function addToCart (name, price) {
    var object = {};
    object.name = name;
    object.price = price;

    shoppingCart.push(object);
    }

    addToCart ('beer', 5);

    function priceCheck(item){
    for (var i = 0; i < shoppingCart.length; i += 1) {

    if (item === shoppingCart[i].name) {console.log(shoppingCart[i].price + " shekels");}

    else {console.log("the searched item is not in the shopping cart array!");}
    }
    }

    function totalPriceCheck(){
    for (var i = 0; i < shoppingCart.length; i += 1) {
    var totalPriceOf = shoppingCart[i].price; 

    var myTotal = 0;  

    for(var i = 0, len = totalPriceOf.length; i < len; i++) {
    myTotal += totalPriceOf.price;  
    }

    console.log(myTotal);
    }}

    totalPriceCheck();  

2 个答案:

答案 0 :(得分:1)

You can use reduce to get the sum :

function totalPriceCheck(){
  return shoppingCart.reduce(
    (acc, elem)=>acc + elem.price, 
    0
  );
}

答案 1 :(得分:1)

I can't understand your question properly but I think you need output like this. I am doing some changes in your code, please refer below code

output of below code is :- 15

if you add addToCart('beer', 5); than out put will be 20

var shoppingCart = [];

function addToCart(name, price) {
    var object = {};
    object.name = name;
    object.price = price;

    shoppingCart.push(object);
}

addToCart('beer', 5);
addToCart('beer', 5);
addToCart('beer', 5);

function totalPriceCheck() {
    var myTotal = 0;
    for (var i = 0; i < shoppingCart.length; i += 1) {
        var totalPriceOf = shoppingCart[i].price;
        myTotal += totalPriceOf;
    }
    console.log(myTotal);
}

totalPriceCheck();