如果我从for循环内部推送它,我的javascript 2d数组似乎总是返回0的长度。无论我做什么,都会给出0的长度。
我不知道我已经在mapList中输入了多少设备,所以我需要获得数组的长度,但我不能。在例子,codepens,jsfiddles等在线,我看到类似的代码,它正常工作。我不明白我做错了什么。
有人可以解释为什么它的长度不会随着每个新阵列的增加而增加吗?
使用Javascript:
var mapList = [];
function getMarkers(){
$.getJSON('getDeviceCoords.php', function(jd) {
for (var i = 0, len = jd.devices.length; i < len; i++) {
mapList.push([jd.devices[i].nickname, jd.devices[i].latitude, jd.devices[i].longitude]);
});
}
console.log(mapList); // [] but expands to show each array entry
console.log(mapList.length); // 0
JSON响应:
{
"status": "OK",
"devices": [
{
"ID": "12:34:56:78:90:FF",
"nickname": "Device 1",
"latitude": "12.3456",
"longitude": "12.3456"
},
{
"ID": "FF:FF:FF:FF:FF:FF",
"nickname": "Device 2",
"latitude": "12.3465",
"longitude": "12.3465"
}
]}
控制台输出:
▼[]
►0: (3) ["Device 1", "12.3456", "12.3456"]
►1: (3) ["Device 2", "12.3465", "12.3465"]
length: 2
►__proto__:Array(0)
0
答案 0 :(得分:1)
在异步回调完成之前,您正在记录mapList
数组的长度。试试这个:
var mapList = [];
function getMarkers(){
$.getJSON('getDeviceCoords.php', function(jd) {
for (var i = 0, len = jd.devices.length; i < len; i++) {
mapList.push([jd.devices[i].nickname, jd.devices[i].latitude, jd.devices[i].longitude]);
}
console.log(mapList);
console.log(mapList.length);
});
}