为什么在再次使用之前必须将字典类型数据初始化为空

时间:2017-05-07 20:30:18

标签: jquery json dictionary

我有这个JSON数据,我根据用户输入动态更新数据。我的问题是为什么我必须在存储数据时初始化一个空的字典变量?

因为当我初始化它时,它只会覆盖该特定键的所有值的数据。我在谈论代码是这样的:

function updateThirdLayer() {

_data = global_json_data;

$.each(_data, function(key1, value1) {
    if (key1 == 'questions') {
        $.each(value1, function(key2, value2) {
            if (value2["choices_qty"] > 1) {
                choices = {};
                choice = {};
                for (xyz = 0; xyz < value2["choices_qty"]; xyz++) {

                    choice["id"] = value2["choices"][xyz]["id"];
                    choice["description"] = $("#q" + key2 + "_a" + xyz).val();
                    choices[xyz] = choice;
                    console.log(JSON.stringify(choice));
                    console.log(JSON.stringify(choices));
                }
                console.log(JSON.stringify(choices));
            }
        });
    }
});
global_json_data = _data;

}

但是当我每次使用变量初始化它时它会给我正确的输出。代码是这样的:

function updateThirdLayer() {

_data = global_json_data;

$.each(_data, function(key1, value1) {
    if (key1 == 'questions') {
        $.each(value1, function(key2, value2) {
            if (value2["choices_qty"] > 1) {
                choices = {};
                for (xyz = 0; xyz < value2["choices_qty"]; xyz++) {
                    choice = {};
                    choice["id"] = value2["choices"][xyz]["id"];
                    choice["description"] = $("#q" + key2 + "_a" + xyz).val();
                    choices[xyz] = choice;
                    console.log(JSON.stringify(choice));
                    console.log(JSON.stringify(choices));
                }
                console.log(JSON.stringify(choices));
            }
        });
    }
});
global_json_data = _data;

}

JSON STRUCTURE:

{
"blah":"blah",
"questions":
 {
  0:
  {
  "blah":"blah",
  "choices":
   {
    0:
    {
     "id":"",
     "description":"desc"
    } 
   }
  }
 }
}

注意:我知道我构建数据的方式是一种糟糕的方式,但请不要理会它。我的问题是解释为什么它的工作原理

感谢很多人!

编辑:

当我使用上面第一个代码块时,所有选项的“描述”成为选择描述中最后一项的值,用于选择中每个描述键的所有数据

global_json_data:

{"title":"1","total_qty":"3","per_page":"2","questions":{
  "0": {"description":"1","type_id":"1","choices_qty":1,"choices":null},
  "1": {"description":"2","type_id":"1","choices_qty":1,"choices":null},
  "2": {"description":"3","type_id":"2","choices_qty":"4","choices":{
      "0":{"id":"","description":""},
      "1":{"id":"","description":""},
      "2":{"id":"","description":""},
      "3":{"id":"","description":""}
       }
   }
 }}

0 个答案:

没有答案