When iterating over values, why does typeof(value) return "string" when value is a number? Javascrip

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2010-05-29T04:03:24Z Indexed on 2010/05/29 4:12 UTC
Read the original article Hit count: 148

Filed under:
|
|

I'm using Google Chrome for this test: Contrary to intuition, the first loop alerts "string" 3 times, while the second loop alerts "number" 3 times.

numarray = [1, 2, 3];

//for-each loop
for(num in numarray) 
    alert(typeof(num));

//standard loop
for(i=0; i<numarray.length; i++) 
    alert(typeof(numarray[i]));

I was expecting both loops to alert "number" 3 times. How is the first loop implemented in Javascript? In other words, if the for-each is syntactic sugar, what is its equivalent using a standard loop?

Also, is there some way to iterate over an object's namespace using a standard loop? I'm looking to touch every one of some object's methods and attributes using a loop of the second kind. I'm new to Javascript and any help is highly appreciated, thanks.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about foreach