我正在尝试使用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
。
感谢您的帮助。
答案 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);