JavaScript数组未返回正确的长度 [英] Javascript array not returning the correct length

查看:43
本文介绍了JavaScript数组未返回正确的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能真是愚蠢,但对于我的一生,我看不到.

This is probably something really stupid but for the life of me i can't see it.

我有用字符串填充数组的代码,然后ii想要遍历该数组并将值添加为select控件中的as选项.但是由于某种原因,当我调用length属性时,它返回0,但是如果我使用console.dir在控制台中显示该数组,则其中包含数据.

I have code that fills an array with strings and ii then want to loop through the array and add the values to as options in a select control. But for some reason when i call the length property it returns 0, but if i use console.dir to display the array in the console it has data in it.

这是代码:

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数据,您可以看到其中的数据:

Here's the cosole.dir data which you can see has data:

//secotrs
Array[0]
0: "Industrial"
1: "Commercial"
length: 2
__proto__: Array[0]

推荐答案

您正在进行Ajax调用.Ajax是异步!调用后( for 循环)后的代码在执行 回调之前运行(并填充了数组).

You are making an Ajax call. Ajax is asynchronous! The code after the call (the for loop) is run before the callback executed (and the array is populated).

在回调中放置所有依赖于 sectors 的代码:

Put all the code that depends on sectors in the callback:

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 的输出:正如我所假设的.当您在控制台中展开条目时(而不是在进行调用时),将获取对象的属性.

Regarding the output of console.dir: It is as I assumed. The properties of the object are fetched when you expand the entry in the console, not when you make the call.

示例:

> a = [];
  []
> console.dir(a)
  ▸ Array[0]
    undefined
> a.push(5)
  1

当我现在单击 Array [0] 旁边的标记时,我得到:

When I now click the marker next to Array[0], I get:

▾ Array[0]
   0: 5
   length: 1
  ▸ __proto__: Array[0]

在以后添加时(在 console.dir 调用之后),可能希望它不会显示 0:5 .

where one would expect that it does not show 0: 5 as it was added later (after the console.dir call).

这篇关于JavaScript数组未返回正确的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆