javascript - 对象变量属性未定义,即使它不是
问题描述
我正在尝试使用变量读取 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"}
解决方案
解决了,因为设置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
});
推荐阅读
- angular - 插入组件/嵌入式视图作为 ViewContainerRef 的第一个子级,该子级在组件的模板中具有子级
- java - Http 响应未能获取响应正文
- javascript - TypeScript:可选参数的构造函数后备值
- python - 如何在 Flask 中选择按钮后正确触发 random.choice()?
- java - 如何确定我的 Java SpringApplication 由于 proxyBeansMethods 而无法运行的问题?
- opencv - 查找 OpenCV 级联分类器检测到的对象的边界
- javascript - Puppeteer-core 保存的密码 - 也许使用当前实例?
- python - Pandas 比较两个数据框并查找重复元素
- flutter - Flutter Row 小部件通过切断剩余区域解决 RenderFlex 溢出问题
- javascript - 具有复杂嵌套对象的数组解构