首页 > 解决方案 > 对象变量属性未定义,即使它不是

问题描述

我正在尝试使用变量读取 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"}

在此处输入图像描述

标签: javascriptjson

解决方案


解决了,因为设置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

  });

推荐阅读