修訂版從原來的問題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