【问题标题】:Javascript string instead of object expectedJavascript字符串而不是预期的对象
【发布时间】:2012-02-18 00:55:27
【问题描述】:
var x = {};
x.a = {y:5};
x.b = {z:6};

for (prop in x) console.log(typeof prop); // returns "string". Why not "object"?

它不应该返回对象吗?我该如何解决这个问题?

【问题讨论】:

标签: javascript string object


【解决方案1】:

如果你输出道具本身,你会看到它们是键:“a”,“b”。

【讨论】:

  • prop 在循环中得到的值是字符串“a”,然后是字符串“b”。
  • 对,但是为什么“a”是对象的时候得到的是字符串呢?
  • @user1019031: "a" 不是一个对象,它是一个字符串。 x.a(或x["a"])是一个对象。看看我在评论中链接到的文档。
【解决方案2】:

所有这些回答都是正确的,但也许你会看到一个更正的例子更好:

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}

【讨论】:

  • 嗯,谢谢!正是我需要了解它。
【解决方案3】:

它返回属性的名称。

【讨论】:

    【解决方案4】:

    将最后一行更改为

    for (prop in x) console.log(typeof x[prop]);
    

    x[prop] 部分采用属性名称,称为prop(它是字符串类型)并返回属性x.prop,对于a 和b,它将返回对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 2011-08-06
      • 2014-02-08
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      相关资源
      最近更新 更多