gpt4 book ai didi

javascript - 如何通过使用 jQuery 指定变量来查找 JSON 中的值

转载 作者:行者123 更新时间:2023-12-02 17:55:25 25 4
gpt4 key购买 nike

我有这个简单的 JSON

{"places" : {
"home" : {
"1": "red"
}
}}

我需要获取1值,该值取决于我的主体类的某个变量。 body 等级是可变的。这是我的脚本:

(function(){    
var bodyClass = $('body').attr('class');
function getPlaceValue(){
return $.getJSON('data.json', function(data) {
var placeValue;
placeValue = data.places.bodyClass.1;
return placeValue;
});
}

getPlaceValue().done(function(placeValue){
console.log(placeValue);
});
}).call(this);

我已回复 1 值未定义。出了什么问题,有可能这样做吗?

最佳答案

bodyClass 定义为变量:

var bodyClass = $('body').attr('class');

...但随后尝试读取文字 bodyClass 属性,该属性当然不存在:

placeValue = data.places.bodyClass.1;

此外,you cannot use the dot syntax to access the 1 property :

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)

我想你的意思是:

placeValue = data.places[bodyClass][1];

关于javascript - 如何通过使用 jQuery 指定变量来查找 JSON 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20999288/

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