开发者

JS prototype returns prototype code

开发者 https://www.devze.com 2023-02-06 07:27 出处:网络
Array.prototype.last = function(开发者_C百科) { if(this.length !=0) return this[this.length-1]; }
Array.prototype.last = function(开发者_C百科) { if(this.length !=0) return this[this.length-1]; }
myarray = new Array(1,2,3);
  for(var i in myarray){
  alert(i+'='+myarray[i]);
}

When the above code executes, it correctly alerts each loop, but then at the end another alert pops up with the source of the Array.prototype.last method.

This happens whenever I define any prototype method and I just don't know why !

So I get alerts for: 0=1,1=2,2=3 and then one for:

last=function () {
  if (this.length != 0) {
    return this[this.length - 1];
  }
}


This is because the for-in statement enumerates object properties, included the inherited ones.

That's one of the reasons why using the for-in statement with arrays or array-like objects is considered a bad practice.

Other reasons include that the order of enumeration is not guaranteed by the specification, this means that the index properties might not be visited in the numeric order, for example:

var a = [];
a[1] = 'b';
a[0] = 'a'

for (var prop in a) { console.log(i); }

Most browsers will detect you are trying to iterate over an array, and the properties will be visited in the numeric order, but in IE, the properties will be enumerated in the order that they were created, 1 and then 0.

Also is known that the for-in statement can be slower than a simple sequential loop, because as you know now, it needs to introspect the whole prototype chain of the object, to enumerate the inherited members.

As a general recommendation, always use a sequential loop to iterate this kind of objects.

See also:

  • Enumeration VS Iteration


This is why you never use for(idx in anArray){...} in javascript the for...in loop iterates over all the properties in the object, and an Array is just an object in JS, you added a new property to all instances of Array so it appears as one of the indexes in the for loop.

with arrays generally you should do:

for(var i=0 ; i< anArray.length ; i++){
    //do stuff
}


That is because last is a function which myarray derives from the prototype properties and is indexable. To avoid that you need to check hasOwnProperty i.e.:

for(var i in myarray)
{
  if(myarray.hasOwnProperty(i))
    alert(i+'='+myarray[i]); 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消