There is an object that has a property declared as an object, but when accessing it, it turns out that this property is of the type string. What is the reason for this transformation?

Here is the code:

<script> var test = new Object(); test.property1 = 1; test.property2 = "1"; test.property3 = new Object(); test.property3.property1 = 1; test.property3.property2 = "1"; for (var name in test){ document.write(name + " type: " + typeof name + "<br>"); } </script> 

result:

 property1 type: string property2 type: string property3 type: string // не ясно почему это строковый тип, а не объект? 

    1 answer 1

    Because for (var name in test){} iterates over the keys of the object, not the values ​​of the properties. In such a loop, any key will be a string, respectively, and the typeof key will return the string.

    To iterate the values ​​of properties, you must use a loop (in your case) typeof test[name] .

    • I would paraphrase: the key (property name) in the for loop for..in always a string. - hindmost