为什么我的(关键列表)不能像我想的那样工作?

时间:2014-09-13 23:06:17

标签: javascript

我正在进行CodeSchool的练习之一,我想使用“for in”循环,但是他们使用正常的for循环,我不知道为什么它需要那样

var canyonCows = [
  {name: "Bessie", type: "cow", hadCalf: "Burt"},
  {name: "Bertha", type: "cow", hadCalf: null},
  {name: "Donald", type: "bull", hadCalf: null},
  {name: "Esther", type: "calf", hadCalf: null},
  {name: "Burt", type: "calf", hadCalf: null},
  {name: "Sarah", type: "cow", hadCalf: "Esther"},
  {name: "Samson", type: "bull", hadCalf: null},
  {name: "Delilah", type: "cow", hadCalf: null},
  {name: "Shanaynay", type: "cow", hadCalf: null}
];

Object.prototype.noCalvesYet = function(){
//return true for an object if the object is a cow
  if(this.hadCalf == null && this.type =='cow') return true;
  else return false;
};

Array.prototype.countForBreeding = function(){
  //this block doesn't work
  var count = 0;
  for(c in this)
  {
    if(c.noCalvesYet()) ++count;
  }
  return count;

  //this block does work (when i comment out the above block, naturally)
  // var count = 0;
  // for(var i = 0; i < this.length;++i)
  // {
  //   if(this[i].noCalvesYet())count++;
  // }
  // return count;
};

//find how many cows haven't had a calf yet and use those for breeding
alert(canyonCows.countForBreeding());

2 个答案:

答案 0 :(得分:2)

JavaScript for ... in循环遍历属性名称,而不是属性

无论如何,你的数组是一个实际的数字索引数组,所以你不应该首先使用for ... in

for (var c = 0; c < this.length; ++c) {
  var cow = this[c];
  if (cow.noCalvesYet()) count++;
}

或者:

this.forEach(function(cow) {
  if (cow.noCalvesYet()) count++;
});

答案 1 :(得分:0)

这是接受的答案:

Object.prototype.noCalvesYet = function () {
  if(this.type == "cow" && this.hadCalf == null){
    return true;
  }
  return false;
};
Array.prototype.countForBreeding = function(){
  var numToBreed = 0;
  for(var i = 0; i<this.length; i++){
    if(this[i].noCalvesYet()){
      numToBreed++;
    }
  }
  return numToBreed;
};