嵌套对象的for_in循环javascript不返回预期值

时间:2017-03-30 08:40:49

标签: javascript object nested

我正在尝试使用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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

使用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; }




答案 1 :(得分:0)

使用它:

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

     alert(contentCards.contentCard1.text);