代码不向数组添加对象

时间:2011-10-30 18:44:35

标签: javascript arrays json push

我正在尝试将从JSON文件中检索到的一组对象添加到数组中。我尝试过使用push但结果是一样的。数组的length值仍为0。我究竟做错了什么? JSON解析正常,因为我可以在循环期间获取值。

<script type="text/javascript"> 

//my array
var myArray = new Array();

function performSearch(){

    var url = "http://myjsonurl...";
    var counter = 0;

    $.getJSON(url, function(response){
         $.each(response.data.people, function() {

            //p is the the object to add to the array
            var p = new person(this.name, this.age);

            //tried using myArray.push instead of having a counter, but
            //I get the same length of 0.
            myArray[counter] = p;
            counter++;
        });

    });     

    //always returns 0  
    alert(myArray.length);

}

... 
</script>

4 个答案:

答案 0 :(得分:3)

getJSON()是一个异步函数。它只在你调用它时才开始获取数据,它只在加载后调用给定的函数。因此,在获取任何内容之前调用警报。您应该在.each()函数之后立即获得警报。

答案 1 :(得分:1)

Ajax是异步的。无论取决于JSON需要在回调中发生

function performSearch()
{
    var url = "http://myjsonurl...";
    $.getJSON(url, function(response)
    {
        var myArray = $.map(response.data.people, function()
        {
            return new person(this.name, this.age);
        });

        alert(myArray.length);
    });     

    //always returns 0  
    alert(myArray.length);
    // that's because this code executes before the $.getJSON callback does
}

答案 2 :(得分:1)

在将对象放入其中之前,您将返回该数组。

getJSON方法中使用的回调函数不会立即运行,它会在响应到达时运行。由于两个方法无法同时运行,因此在回调函数运行之前,您将始终退出函数。

您可以在回调函数中访问结果:

<script type="text/javascript"> 

function performSearch(){

  var url = "http://myjsonurl...";

  $.getJSON(url, function(response){

    var myArray = [];

    $.each(response.data.people, function() {
      var p = new person(this.name, this.age);
      myArray.push(p);
    });

    alert(myArray.length);

  });     

}

</script>

答案 3 :(得分:0)

<script type="text/javascript"> 

//my array
var myArray = new Array();
var counter = 0;

function performSearch(){

    var url = "http://myjsonurl...";

    $.getJSON(url, function(response){
         $.each(response.data.people, function() {

            //p is the the object to add to the array
            var p = new person(this.name, this.age);

            //tried using myArray.push instead of having a counter, but
            //I get the same length of 0.
            myArray[counter] = p;
            counter++;

            alert(myArray.length);

        });

    });     


}

... 
</script>