在数组原型中循环

Looping in the Array Prototype

本文关键字:循环 原型 数组      更新时间:2023-09-26

为什么我的代码不能工作?

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

我做错了什么?

这是length不是长度

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