为什么在迭代中会出现原型函数?

时间:2012-06-20 06:36:49

标签: javascript prototype

所以有这个功能

Array.prototype.containsCaseInsensitive = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i].toUpperCase() === obj.toUpperCase()) {
      return true;
    }
  }
  return false;
}

然后我创建了这个数组:

ary = [0,1,2,3];
for (item in ary){
  console.log(ary[item])
}

输出如下:

0
1
2
3
function(obj) {
    var i = this.length;
    while (i--) {
       if (this[i].toUpperCase() === obj.toUpperCase()) {
           return true;
       }
    }
    return false;
 }

为什么迭代中的函数? 谢谢!

5 个答案:

答案 0 :(得分:4)

您的属性是可枚举的(尽管您不应该使用for ... in ...枚举数组的键)。

在兼容ES5的浏览器上,您可以使用Object.defineProperty安全地将该功能添加为不可枚举的属性:

Object.defineProperty(Array.prototype, 'containsCaseInsensitive', {
    value: function() {
        ...
    }
});

答案 1 :(得分:0)

使用for .. in时,数组被视为一个对象,这就是为什么它会显示所有属性。使用常规来达到你想要的效果。

答案 2 :(得分:0)

因为containsCaseInsensitive是数组的成员,并且您正在迭代数组的所有成员。您不应该编写for ... in次迭代来迭代数组中的项目。

答案 3 :(得分:0)

因为for..in输出了对象的所有可枚举属性。

如果只想要数组的值,可以使用:

for (item in ary){
   if ( ary.hasOwnProperty( item ) )
      console.log(ary[item])
}

在支持的环境中,您还可以使用defineProperty将该功能设置为不可枚举,如下所示:

Object.defineProperty( Array.prototype, 'containsCaseSensitive', {
    value: function( obj ) {},
    enumerable: false
    // ^ this is default when you use defineProperty, so you don't need it
    // but it is to show you how that works :-)
} );

但是,通常不建议对数组使用for..in,只能将它用于文字对象。

对于数组,建议使用:

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

或者,如果支持:

arr.forEach( function( el ) {
    console.log( el );
} );

答案 4 :(得分:0)

您正在迭代对象的所有属性。您需要查看this