0

JS菜鸟在这里。如何设置一个变量等于所有三个动物对象的 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
  },

};
4

3 回答 3

1
var key, days = 0;

for (key in food) {
  if ( Object.prototype.hasOwnProperty.call(food, key) ) {
    days += foods[key].currentDays;
  }
}
于 2013-04-10T23:25:43.533 回答
0
var sum = 0;
for (var k in foods) {
    if (foods.hasOwnProperty(k))
        sum += foods[k].currentDays;
}

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

于 2013-04-10T23:24:30.370 回答
0

如果您可以依靠最近的 JavaScript 引擎,您可以使用reduce该类型的方法Array

Object.keys(foods).reduce(function (p,v,i,a) {
    return p + foods[v].currentDays;
}, 0);
于 2013-04-10T23:35:51.280 回答