动态multidimmensional关联数组我从PHP持有类似这样的多行得到一个JSON对象:JavaScript创建从JSON
id | type | amount| age
1 | abc | 1 | 1
2 | def | 2 | 1
3 | def | 4 | 2
4 | def | 13 | 3
我运行它通过JavaScript:
$.ajax({
type: 'POST',
url: "test.php",
dataType: 'json',
success: function (data) {
var arr = [];
for (var i = 0; i < data.length; i++) {
arr[data[i].type][data[i].age] = data[i].ammount;
}
}
});
的想法是获取阵列,如下所示:
arr[def][1] = 2
arr[def][2] = 4
arr[def][3] = 13
arr[abc][1] = 1
arr[abc][2] = 0 // note that this one is just empty because it was not declared from json data.
不幸的是,我收到一个错误:
Uncaught TypeError: Cannot set property '1' of undefined
1是[data[i].age]
如果我改变它的值错误出现与其他数字。
您能得到什么,什么你结束了?为什么你不使用.push? –
我得到json对象,我可以访问所有的属性,即数据[i] .type,所以我可以从数据[3] .type = def中获取。如上所述,我最终会遇到错误。我不能使用推,因为我得到的所有数据是随机顺序 - 使用适当的键我可以很容易地排序 – Kalreg
我认为你应该初始化内部数组。我建议你检查这个问题:http://stackoverflow.com/questions/13725138/javascript-multi-dimensional-dynamic-array。 – kgd