![](/img/trans.png)
[英]JavaScript returning array length of 0, but correct length in console
[英]Javascript array not returning the correct length
这可能真是愚蠢,但对于我的一生,我看不到。
我有用字符串填充数组的代码,然后ii想要遍历该数组并将值添加为select控件中的选项。 但是由于某种原因,当我调用length属性时,它返回0,但是如果我使用console.dir在控制台中显示该数组,则它中包含数据。
这是代码:
var sectors = new Array();
// code to add values
$.getJSON("get/tech_info.php", {uid:json.uid}, function(data){
$.each(data, function(i, json){
if($.inArray(json.area, sectors) == -1)
{
sectors[sectors.length] = json.area;
}
});
});
console.dir(sectors);
var sec = "#mainSectors" + count;
console.log(sectors.length); // returning 0
for ( var i=0; i != sectors.length; i++ ){
console.log("bla bla bla");
$(sec).append(
$("<option></option>").html(sectors[i])
);
}
这是cosole.dir数据,您可以看到其中的数据:
//secotrs
Array[0]
0: "Industrial"
1: "Commercial"
length: 2
__proto__: Array[0]
您正在拨打Ajax电话。 Ajax是异步的 ! 调用( for
循环)之后的代码在执行回调之前运行(并填充了数组)。
将所有依赖于sectors
的代码放在回调中:
var sectors = [];
$.getJSON("get/tech_info.php", {uid:json.uid}, function(data){
$.each(data, function(i, json){
if($.inArray(json.area, sectors) == -1)
{
sectors.push(json.area);
}
});
var sec = "#mainSectors" + count;
console.log(sectors.length); //
for ( var i=0; i != sectors.length; i++ ){
console.log("bla bla bla");
$(sec).append(
$("<option></option>").html(sectors[i])
);
}
});
更新:
关于console.dir
的输出:这是我假设的。 当您在控制台中展开条目时(而不是在进行调用时),将获取对象的属性。
例:
> a = [];
[]
> console.dir(a)
▸ Array[0]
undefined
> a.push(5)
1
现在,单击Array[0]
旁边的标记时,我得到:
▾ Array[0]
0: 5
length: 1
▸ __proto__: Array[0]
其中一个会认为它不显示0: 5
,因为它是后来添加(后console.dir
调用)。
在向数组中添加内容之前,您正在显示length
属性(带有console.log
),因此我想那里的长度是0。 之后,您将循环一个空数组。
此外,如果扇区具有length
,则for ( var i=0; i != sectors.length; i++ )
可以无休止地运行,因为当它不是ectors.length时它会跳过i
并继续前进。 使用i<sectors.length
。
我想为此行sectors[sectors.length] = json.area;
扇区不在范围内var sectors = new Array();
应该在任何功能之外的主要范围内
以下内容不应该:
if($.inArray(json.area, sectors) == -1)
是
if($.inArray(json.area, sectors) != -1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.