Javascript 为什么只记录我的json数据的一部分?
我试图最终在标签中显示json数据。但是,当I console.log记录json数据时,只显示最后两个对象。将数据传递到标签时,仅显示最后一个对象。提前感谢您的帮助 这是我的密码:Javascript 为什么只记录我的json数据的一部分?,javascript,json,titanium,Javascript,Json,Titanium,我试图最终在标签中显示json数据。但是,当I console.log记录json数据时,只显示最后两个对象。将数据传递到标签时,仅显示最后一个对象。提前感谢您的帮助 这是我的密码: var json = { "Question:": " What is my name? ", "Answer:": " James ", "Question:": " What is my age? ", "Answer:": " 31 "
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);
你的问题与钛无关。在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不会对此抱怨,它只会用第二个值覆盖第一个键值我明白了,谢谢!我花了很多时间想知道发生了什么事。我可能需要javascript来制作傻瓜lol。