How to sum the values of a JavaScript object?

后端 未结 14 791
梦如初夏
梦如初夏 2020-11-27 04:03

I\'d like to sum the values of an object.

I\'m used to python where it would just be:

sample = { \'a\': 1 , \'b\': 2 , \'c\':3 };
summed =  sum(sampl         


        
14条回答
  •  庸人自扰
    2020-11-27 04:10

    let prices = {
      "apple": 100,
      "banana": 300,
      "orange": 250
    };
    
    let sum = 0;
    for (let price of Object.values(prices)) {
      sum += price;
    }
    
    alert(sum)

提交回复
热议问题