How to sum the values of a JavaScript object?

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

    You could put it all in one function:

    function sum( obj ) {
      var sum = 0;
      for( var el in obj ) {
        if( obj.hasOwnProperty( el ) ) {
          sum += parseFloat( obj[el] );
        }
      }
      return sum;
    }
        
    var sample = { a: 1 , b: 2 , c:3 };
    var summed = sum( sample );
    console.log( "sum: "+summed );


    For fun's sake here is another implementation using Object.keys() and Array.reduce() (browser support should not be a big issue anymore):

    function sum(obj) {
      return Object.keys(obj).reduce((sum,key)=>sum+parseFloat(obj[key]||0),0);
    }
    let sample = { a: 1 , b: 2 , c:3 };
    
    console.log(`sum:${sum(sample)}`);

    But this seems to be way slower: jsperf.com

提交回复
热议问题