修订版从原来的问题JavaScript对象调查
我想学什么JavaScript对象“看起来像”通过观察它,像这样的属性:
//create object without prototype
var obj = Object.create(null);
//add properties
obj.a = 3;
obj.b = 76.3;
obj.c = { a : 23 , b : true , c : 1};
obj.s = "ABC!";
//output string
var outStr = new String();
for(var prop in obj)
{
outStr += "Property " + prop + " is a " + typeof(obj[prop]) + " with value " + obj[prop] + "\n";
for(var prop1 in obj[prop])
{
outStr += "Property " + prop1 + " is a " + typeof(obj[prop][prop1]) + " with value " + obj[prop][prop1] + "\n";
for(var prop2 in obj[prop][prop1])
{
outStr += "Property " + prop2 + " is a " + typeof(obj[prop][prop1][prop2]) + " with value " + obj[prop][prop1][prop2] + "\n";
for(var prop3 in obj[prop][prop1][prop2])
{
outStr += "Property " + prop3 + " is a " + typeof(obj[prop][prop1][prop2][prop3]) + " with value " + obj[prop][prop1][prop2][prop3] + "\n";
for(var prop4 in obj[prop][prop1][prop2][prop3])
{
outStr += "Property " + prop4 + " is a " + typeof(obj[prop][prop1][prop2][prop3][prop4]) + " with value " + obj[prop][prop1][prop2][prop3][prop4] + "\n";
}
}
}
}
}
alert(outStr);
其中给出输出:
Property a is a number with value 3
Property b is a number with value 76.3
Property c is a object with value [object Object]
Property a is a number with value 23
Property b is a boolean with value true
Property c is a number with value 1
Property s is a string with value ABC!
Property 0 is a string with value A
Property 0 is a string with value A
Property 0 is a string with value A
Property 0 is a string with value A
Property 1 is a string with value B
Property 0 is a string with value B
Property 0 is a string with value B
Property 0 is a string with value B
Property 2 is a string with value C
Property 0 is a string with value C
Property 0 is a string with value C
Property 0 is a string with value C
Property 3 is a string with value !
Property 0 is a string with value !
Property 0 is a string with value !
Property 0 is a string with value !
现在,它的行为与我期望的除了String属性之外的每个属性完全相同obj.s =“ABC!”;
我明白obj.s包含属性(键和值):
“0”= “A”
“1”= “B”
“2”=“ C“
”3“=”!“
从前面的回答(非常感谢@pimvdb和@deestan)我收集到,因为每个属性值都是字符串,它们每个都包含属性键“0”,它本身必须包含属性键“0”等,等?这就是为什么我要为字符串属性写出额外的行。
所以我的问题现在变成:
应的所有属性的值,在某些点的类型,最终恢复到原始类型像数或布尔停止这种递归链?我正在考虑实际上持有这个对象的内存,当我开始写这个小测试脚本来“查看”对象时,我基本上想看到所有的基元以及对象如何存储它们,但实际上并不存在无限的字符串分配到字符串到字符串...我想它只是存储为字符串对象与它的4个字符(或5如果theres字符串字符的结尾太0)
谢谢你,这是非常有帮助的答案我一定会从现在开始使用JavaScript控制台。 – 0xor1 2012-03-09 22:19:25