2

假设我想使用 to_html() 方法扩展 Array:

Array.prototype.to_html = function() {
  console.log(this.length);

  for(var i in this) {
    console.log(this[i]);
  }
};

我有一个数组:

var arr = [1, 2, 3];

调用arr.to_html()时,控制台中的第一行看起来不错:

3

到目前为止,一切都很好。但这里有以下几行:

1
2
3
function() {
  console.log(this.length);

  for(var i in this) {
    console.log(this[i]);
  }
}

哎呀,第四元素从何而来?我怎样才能摆脱它?

4

3 回答 3

4

试试这个,以确保你只迭代数组项

for(var i = 0; i < this.length; i++) {
    console.log(this[i]);
  }

for in将迭代对象的所有属性。它还包括您在原型上定义的属性/方法

于 2013-07-01T02:54:55.353 回答
1

Javascript for-in 循环获取对象的所有属性。但是Arrays 具有不来自数字索引的属性。尝试ithis[i]. 您将看到至少一个以字符串命名的属性。

于 2013-07-01T02:56:52.703 回答
0

在大多数情况下,更希望使用hasOwnProperty避免查找原型链。以下代码应为您提供预期的结果。

for (var i in this) {
    if (this.hasOwnProperty(i)) {
        console.log(this[i]);
    }
}
于 2013-07-01T03:58:39.507 回答