为什么只有我的json数据的一部分被记录

Why is only part of my json data being logged?

本文关键字:一部分 记录 数据 json 我的 为什么      更新时间:2023-09-26

我试图最终有我的json数据显示在一个标签。但是,当我console.log json数据时,只显示最后两个对象。当我将数据传递给标签时,只显示最后一个对象。提前感谢任何帮助!

下面是我的代码:
var json = 
    {
        "Question:": " What is my name? ",
        "Answer:": " James ",
        "Question:": " What is my age? ",
        "Answer:": " 31 "
    };
for (var key in json)
{
    if (json.hasOwnProperty(key))
    {
        console.log(key + " = " + json[key]);
    }
}
var label = Ti.UI.createLabel({
    text: key + json[key]
});

win3.add(label);

你的问题与Titanium无关。在JavaScript字典中,你不能有两个具有不同值的相同键。为了演示您犯的错误,我将重写您的第一行:

var json = {};
json["Question:"] = " What is my name? ";
json["Answer:"] = " James ";
// We are fine untill now.
json["Question:"] = " What is my age? ";
json["Answer:"] = " 31 ";
// Here you overwrote values for keys "Question:" and "Answer:" which were set above.

为了解决您的问题,我将您的json字典更改为字典数组:

var i, key, label;
var json = [
    {
        "Question:": " What is my name? ",
        "Answer:": " James ",
    },
    {
        "Question:": " What is my age? ",
        "Answer:": " 31 "
    }
];
for (i in json) {
    for (key in json[i]) {
        label = Ti.UI.createLabel({
            text: key + json[i][key]
        });
        win3.add(label);
    }
}

你的json对象键是重复的,javascript不会抱怨这个,它只会用第二个值覆盖第一个键值