在Array Prototype中循环

时间:2014-08-01 14:04:15

标签: javascript arrays loops for-loop prototype

为什么我的代码不起作用?

var canyonCows = [
  {name: "Bessie", type: "cow", hadCalf: "Burt"},
  {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}
];

Array.prototype.countCattle = function(type){
  var counter = 0;
  for(var i=0;i<this.lenght;i++){
    if (this[i]["type"]==type){
      counter++;
    }
  }
  return counter;
};

console.log(canyonCows.countCattle("cow"));

当我运行它时,我得到0而不是3的输出。

我做错了什么?

1 个答案:

答案 0 :(得分:5)

length没有长度。

由于拼写错误,循环不起作用。