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

标签 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

感谢您的帮助。

最佳答案

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

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

关于javascript - 嵌套对象javascript的for_in循环不返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43112648/

相关文章:

javascript - 不使用带有 Jquery 事件的匿名函数

php - 将 PHP 对象传递给 javascript

java - 在java中创建接口(interface)对象

javascript - 灯箱 5 在 ajax 页面加载中不起作用

javascript - 隐藏/显示在 Android 应用程序上不起作用的表单元素

javascript - 用 Leaflet 创建一个圆(使用正半径)

Javascript toSource 然后 toObject

python - 编目词典列表

javascript - 将 HTML 表单数据转换为嵌套 JSON

c# - C# 嵌套方法调用的优点(和缺点)