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