var x = {};
x.a = {y:5};
x.b = {z:6};
for (prop in x) console.log(typeof prop); // returns "string". Why not "object"?
不應該返回對象嗎?我如何解決這個問題?JavaScript字符串,而不是預期的對象
var x = {};
x.a = {y:5};
x.b = {z:6};
for (prop in x) console.log(typeof prop); // returns "string". Why not "object"?
不應該返回對象嗎?我如何解決這個問題?JavaScript字符串,而不是預期的對象
如果你輸出道具的自己,你會看到他們是關鍵:「a」,「b」。
你是什麼意思? – user1019031 2012-02-18 00:58:21
'prop'在循環中得到的值是字符串「a」,然後是字符串「b」。 – 2012-02-18 00:59:25
正確,但爲什麼當「a」是對象時它會得到字符串? – user1019031 2012-02-18 01:01:05
它返回屬性的名稱。
你的最後一行更改爲
for (prop in x) console.log(typeof x[prop]);
的x[prop]
部分以屬性的名字,叫prop
(其類型爲字符串),並返回屬性x.prop
,這對於a和b的情況下,將返回目的。
所有這些反應是正確的,但也許你會與一個更正例子看得更清楚:
var x = {};
x.a = {y:5};
x.b = {z:6};
for (prop in x) console.log(typeof prop); // returns "string"
for (prop in x) console.log(prop); // returns "a", then "b"
for (prop in x) console.log(typeof x[prop]); // returns "object"
for (prop in x) console.log(x[prop]); // returns {y:5}, then {z:6}
啊,感謝你了!正是我需要我的頭腦才能解決它。 – user1019031 2012-02-18 01:05:10
你應該看看'prop'是什麼:http://jsfiddle.net/NnLrh/1/ – 2012-02-18 00:57:39
如何閱讀[一些文檔](https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in)? – 2012-02-18 00:58:20