How to sum the values of a JavaScript object?

后端 未结 14 779
梦如初夏
梦如初夏 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:07

    We can iterate object using in keyword and can perform any arithmetic operation.

    // input
    const sample = {
        'a': 1,
        'b': 2,
        'c': 3
    };
    
    // var
    let sum = 0;
    
    // object iteration
    for (key in sample) {
        //sum
        sum += (+sample[key]);
    }
    // result
    console.log("sum:=>", sum);

提交回复
热议问题