我试图使用变量读取json对象的属性。如果我使用变量,我得到错误,而如果我使用属性,它可以工作。
JSON:
{
"homebrews": {
"books": {
"title": "text."
},
"cards": {
"template": {
"id": 0,
"name": "myName"
}
}
}
}函数称为
createHomebrew('card');函数:
function createHomebrew(type) {
var homebrew;
$.getJSON('/data-files/templateHomebrew.json', function(json) {
var id = type + 's'; // cards
homebrew = json.homebrews[id].template // json.homebrews[id] is undefined
});相反,
console.log(json.homebrews.cards.template); // Object { id: 0, name: "myName"}

发布于 2021-08-13 06:10:17
解决了,因为设置id = "cards"有效,由于某种原因,使用createHomebrew('card')调用的函数没有识别出卡为字符串,尽管console.log(typeof id)返回了字符串。所以我加入了id = id.toString();
function createHomebrew(type) {
var homebrew;
$.getJSON('/data-files/templateHomebrew.json', function(json) {
var id = type + 's';
id = id.toString();
homebrew = json.homebrews[id].template
});https://stackoverflow.com/questions/68764446
复制相似问题