【问题标题】:for_in loop for nested object javascript don't return expected values [duplicate]嵌套对象javascript的for_in循环不返回预期值[重复]
【发布时间】:2017-08-24 01:41:53
【问题描述】:

我正在尝试使用 for_in 循环遍历 JS 对象。 这似乎将找到的值(contentCard1)作为纯文本返回。 我无法让它打印 val.text

var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}

记录val.text 给我undefined,只记录val 给我contentCard1

感谢您的帮助。

【问题讨论】:

  • 这不是真正的 that 问题的重复,尽管显然存在重叠。
  • @nnnnnn 我很抱歉。 :-) 仍然会持有投票,因为 dupe 回答了如何遍历嵌套对象。

标签: javascript object nested


【解决方案1】:

使用for ... in,您正在迭代contentCards 的键。对于访问,您需要带有bracket notation 的对象和密钥。

contentCards[val].text
//          ^^^^^

var contentCards = { contentCard1: { text: "text in here", date: "date in here" } };

for (var val in contentCards) {
    console.log(contentCards[val].text);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    用过这个:

     var contentCards = {
                contentCard1: { text: "text in here", date: "date in here" }
            }
    
         alert(contentCards.contentCard1.text);
    

    【讨论】:

    • 嗯?如果您不使用迭代器变量而是直接访问特定的嵌套属性,那么循环的意义何在?
    • 是的。但我认为你有 contentCards 作为列表
    • 再一次,如果你有val in contentCards,然后从不使用val,那么循环的意义何在?每次迭代都会提醒相同的特定值。
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多