How to sum the values of a JavaScript object?

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

    I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:

    var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
    var parskey = 0;
    for (var key in array) {
        parskey = parseInt(array[key]);
        sum += parskey;
    };
    return(sum);
    

提交回复
热议问题