Mostafa Farghaly
Mostafa Farghaly

Reputation: 1519

JavaScript Array reflection

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

Upvotes: 3

Views: 965

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186562

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.

Upvotes: 7

vava
vava

Reputation: 25371

You can't loop through native methods.

Upvotes: 3

Related Questions