Sum all properties in object

后端 未结 8 1822
礼貌的吻别
礼貌的吻别 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 04:10

    1. Iterate over the object properties using for(var in)
    2. Use parseInt since some of the integers are in string form

    var obj = {"speed":299,"equipment":49,"teleabb":49,"additional":50,"optional":"299"};
    var sum = 0;
    
    for(var key in obj){
      sum += parseInt(obj[key]);
      }
    
    document.write(sum);

提交回复
热议问题