gpt4 book ai didi

javascript - 访问嵌套 json 对象的属性返回未定义

转载 作者:行者123 更新时间:2023-12-03 07:00:30 24 4
gpt4 key购买 nike

var validCoins = {
"nickel": {
"weight": 5.00,
"diameter": 21.21,
"thickness": 1.95,
"value": 0.05
},
"dime": {
"weight": 2.27,
"diameter": 17.91,
"thickness": 1.35,
"value": 0.10
},
"quarter": {
"weight": 5.67,
"diameter": 24.26,
"thickness": 1.75,
"value": 0.25
}
};

方法一:

Object.keys(validCoins).forEach(function(coinType) {
alert(coinType.weight);
}

方法2:

for (var key in validCoins){
//Checking for hasOwnpProperty here doesn't make a difference
alert(key["weight"]);
}

这些似乎都不起作用,它返回未定义,我错过了什么? (我是否必须导入库或其他东西?)我打算使用纯 JavaScript 来做到这一点。

最佳答案

var validCoins = {
"nickel": {
"weight": 5.00,
"diameter": 21.21,
"thickness": 1.95,
"value": 0.05
},
"dime": {
"weight": 2.27,
"diameter": 17.91,
"thickness": 1.35,
"value": 0.10
},
"quarter": {
"weight": 5.67,
"diameter": 24.26,
"thickness": 1.75,
"value": 0.25
}
};

for (var key in validCoins) {
if (validCoins.hasOwnProperty(key)) {
alert(validCoins[key].weight);
}
}

Fiddle

关于javascript - 访问嵌套 json 对象的属性返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com