如果有人能解释为什么alertbox不返回数组而是空的??
var response = new Array();
response[0] = new Array();
response[1] = new Array();
response[2] = new Array();
response[0]["Id"] = 1;
response[0]["StreetAddress"] = 'xxx';
response[0]["Place"] = 'yyy';
response[1]["Id"] = 2;
response[1]["StreetAddress"] = 'xxx';
response[1]["Place"] = 'yyy';
response[2]["Id"] = 3;
response[2]["StreetAddress"] = 'xxx';
response[2]["Place"] = 'yyy';
$.each(response , function(key1, value1) {
alert(value1);
});
实际上,我将从Web服务中获得这种数组,并且我需要循环到此数组中以检索数据。
但我不明白为什么循环不能正常工作。
提前谢谢各位。
这不是一个多维数组,而是一个无效的代码。Arrays
和Objects
(哈希)在JavaScript(以及大多数其他语言)中是不同的东西,而不是在PHP中。
所以你应该在顶部写下以下内容:
var response = new Array();
response[0] = new Object();
response[1] = {}; // it's the same new Object()
response[2] = new Object();
你可以像以前一样迭代:
$.each(response, function (index, obj) {
$.each(obj, function (key, value) {
console.log(key);
console.log(value);
});
});
如果你尝试:console.log(response)…你会看到数组是空的,看起来数组的格式不好。
为什么不使用JSON格式呢?
var response = [{
"Id":"1",
"StreetAddress": "xxx",
"Place":"yyy"
},
{
"Id":"2",
"StreetAddress": "xxx2",
"Place":"yyy2"
},
{
"Id":"3",
"StreetAddress": "xxx3",
"Place":"yyy3"
}
]
console.log(response);
//you'll get an object: [Object { Id="1", StreetAddress="xxx", Place="yyy"}, Object { Id="2", StreetAddress="xxx2", Place="yyy2"}, Object { Id="3", StreetAddress="xxx3", Place="yyy3"}]
//iterate over
for(var x=0; x < response.length; x++){
console.log("ID: " + response[x].Id + " StreetAddress: " + response[x].StreetAddress + " Place: " + response[x].Place);
}
您不应该在Javascript中使用这样的数组。数组采用数字索引。如果你写
response[1]["Id"] = 2;
您正在向响应[1]数组添加一个属性
编辑-我读了一点更好的你的简历。它指出:
//仅供参考:输出是一个键数组值对(例如响应[0].Id)密钥为:
所以你有一个对象数组。
这将映射您将收到的数据。
var response = new Array;
response[0] = new Object();
response[1] = new Object();
response[2] = new Object();
response[0]["Id"] = 1;
response[0]["StreetAddress"] = 'xxx';
response[0]["Place"] = 'yyy';
response[1]["Id"] = 2;
response[1]["StreetAddress"] = 'xxx';
response[1]["Place"] = 'yyy';
response[2]["Id"] = 3;
response[2]["StreetAddress"] = 'xxx';
response[2]["Place"] = 'yyy';
你可以这样访问它们:
jQuery.each(response, function(key, value){
for (key2 in value[key]){
if (value[key].hasOwnProperty(key2)){
alert(mine[key2])
}
}
});