如何在 for...in 中获得嵌套对象 属性 的正确 属性?

How to get the right property of a nested object property in a for...in?

给定以下代码段:

let PARENT = {
  CHILD_1: {
    no: '1',
    page: 3,
    toString: function(){ return this.no; } },
  CHILD_2: {
    no: '2',
    page: 4,
    toString: function(){ return this.no; } },
}
console.log( JSON.stringify(PARENT, null, 1) )

for ( let c in PARENT ) {
  // c is a CHILD_n object here, right?

  console.log(c)  // why 'CHILD_n' instead of 'no' from toString()?
  console.log(c.page)  // why undefined instead of 'page'?
}

我没有得到预期的结果:

  1. 为什么 c 解析为 CHILD_n 属性 的名称而不是 toString() 返回的值?
  2. 为什么是c.pageundefined? 1. c 不是一个具有可用属性的 CHILD_n 对象吗?
  3. 如何获取期望值?

如评论中所述,for... in 遍历键;即字符串 'CHILD_1''CHILD_2' 与对象相对。

for... of 迭代值,但是,您不能直接迭代对象,因为对象是不可迭代的。 for (value of {}) {} 会抛出错误。

相反,您必须通过例如获取可迭代的值列表Object.values 在迭代之前使用 for... of.

最后,toString 不会被 console.log 自动调用,因此您必须显式调用它。

let PARENT = {
  CHILD_1: {
    no: '1',
    page: 3,
    toString: function(){ return this.no; } },
  CHILD_2: {
    no: '2',
    page: 4,
    toString: function(){ return this.no; } },
};

for ( let c of Object.values(PARENT) ) {
  console.log(c);
  console.log(c.toString());
  console.log(c.page);
}