本文介绍了如何求和JavaScript对象的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对一个对象的值求和。
I'd like to sum the values of an object.
我习惯了python的位置:
I'm used to python where it would just be:
sample = { 'a': 1 , 'b': 2 , 'c':3 };
summed = sum(sample.itervalues())
以下代码有效,但它是很多代码:
The following code works, but it's a lot of code:
function obj_values(object) {
var results = [];
for (var property in object)
results.push(object[property]);
return results;
}
function list_sum( list ){
return list.reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
}
function object_values_sum( obj ){
return list_sum(obj_values(obj));
}
var sample = { a: 1 , b: 2 , c:3 };
var summed = list_sum(obj_values(a));
var summed = object_values_sum(a)
我错过了什么明显的,或者这只是它的方式是什么?
Am i missing anything obvious, or is this just the way it is?
推荐答案
你可以将它全部放在一个函数中:
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)}`);
但这似乎慢一点:
这篇关于如何求和JavaScript对象的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!