Sum all properties in object

后端 未结 8 1913
礼貌的吻别
礼貌的吻别 2021-01-15 03:38

I have the following object:

{\"speed\":299,\"equipment\":49,\"teleabb\":49,\"additional\":50,\"optional\":\"299\"}

I want to sum all this

8条回答
  •  情歌与酒
    2021-01-15 04:08

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    
    
    function sum(obj){
        var sum = 0;
        for(var key in obj){
          if (obj. hasOwnProperty(key)) {
              sum += parseInt(obj[key]) || 0;  
           }
        }
        return sum
    }
    
    console.log(sum(obj));
    

    parseInt(obj[key]) || 0; is important id the value is not a number

提交回复
热议问题