如何对不同对象的属性求和?

时间:2013-04-10 23:22:30

标签: javascript object

JS noob在这里。如何设置一个等于所有三个动物对象的currentDays属性总和的变量?

var foods = {

chicken: {
  'days': 1349.5,
  'deaths': 28.63,
  'currentDays': 1349.5,
  'currentDeaths': 28.63
  },

eggs: {
  'days': 456.25,
  'deaths': 1.733,
  'currentDays': 456.25,
  'currentDeaths': 1.733
  },

pork: {
  'days' :112.5,
  'deaths': .445,
  'currentDays': 112.5,
  'currentDeaths': .445
  },

};

3 个答案:

答案 0 :(得分:1)

var key, days = 0;

for (key in food) {
  if ( Object.prototype.hasOwnProperty.call(food, key) ) {
    days += foods[key].currentDays;
  }
}

答案 1 :(得分:0)

var sum = 0;
for (var k in foods) {
    if (foods.hasOwnProperty(k))
        sum += foods[k].currentDays;
}

JSFiddle:http://jsfiddle.net/dWCAu/

答案 2 :(得分:0)

如果您可以信赖最近的JavaScript引擎,则可以使用reduce类型的Array方法:

Object.keys(foods).reduce(function (p,v,i,a) {
    return p + foods[v].currentDays;
}, 0);