3

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You can't loop through native methods.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.