views:

106

answers:

2

how to loop through JavaScript Array member functions, the following code doesn't work :(

for (var i in Array.prototype){
    alert(i)
} //show nothing 

for (var i in []){
   alert(i)
} // show nothing
+3  A: 

You can't loop through native methods.

vava
+7  A: 

None of the native prototypal properties are enumerable, but you can find out exactly what you're looking for in the ECMA spec:

http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

You can only enumerate through properties which you defined, eg:

Object.prototype.foo = function(){};

x = {};

for ( var prop in x ) {
    alert( prop );
}

would alert:

foo

Another useful tip is that you can use object.hasOwnProperty( property ) inside a for..in loop to branch only if the object directly owns a property, and the property does not descend from the constructor's prototype, of which all objects pretty much descend from Object.prototype.

meder