为什么我的数组“未定义?”

时间:2011-12-07 00:18:16

标签: javascript asynchronous

在我一直在工作的主要应用程序中,以及Stack Overflow专家已经成为救星,我决定通过将主要例程的SortArray分支拆分为其中来避免一些我见过的异步并发症。自己的功能。在函数返回结果之前显示完美结果的测试。

这为我节省了一些处理的方法是我可以在之前对数组进行排序,然后将其发送到主处理函数中。这样,在整个ProcessArray函数中对所有数组进行相同的处理。

在下面的代码示例中,我展示了当前的结构,这是我对给出的建议的解释(最近由jfriend00提供)。我做了两个$ .getJSON调用,第二个是第一个的成功子句,在我结束第一个getJSON调用之前(此时我已经测试并验证了在此处未显示的处理过程中创建的数组),我调用SortArray在其中一个数组上,然后将其传递给将结果发送到ProcessArray的例程。

尽管SortArray代码本身取得了成功,但通过这种方式进入ProcessArray的数组被标记为“未定义”。如果这不是异步处理的问题,我认为它是数组引用的问题。但我不知道如何解决它。

function buildTree(centralID) {
  $(document).ready(function(){
    $.getJSON('MurakiMaida.json', function(data) {
        $.each(data.person, function(i, xdata) {
        ...create a small set of arrays
        }); //end of first $.each() routine
        $.getJSON('MurakiMaida.json', function(data) {
            $.each(data.person, function(i, xdata) {
            ...use an array just created to create another
            }); //end of second each()
        }); //end of second getJSON
        $("#spchildren").html(ProcessArray(SortArray(childIDs, true), centralID, false));
    }); //end of first getJSON
}); //document.ready
}

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的代码(一个很大的if),那就是asynch处理的问题。你的第二个Ajax调用的结果func正在创建“子”数组,对吗?

但Ajax调用的结果func直到稍后才被调用。您正在调用ProcessArray函数。

<强>加入 也许这会有所帮助:

您的代码(如果我理解正确的话)与以下内容完全相同,只是我命名函数而不是内联定义它们:

var async_function_1 = function(data) {
   $.each(data.person, function(i, xdata) {
   ...create a small set of arrays
   }); //end of first $.each() routine

   $.getJSON('MurakiMaida.json', async_function_2);

   $("#spchildren").html(ProcessArray(SortArray(childIDs, true), centralID, false));
   // See the problem? You are calling ProcessArray before async_function_2
   // has a chance to run. 
} 

var async_function_2 = function(data) {
   $.each(data.person, function(i, xdata) {
   ...use an array just created to create another
   }); //end of second each()
};

function buildTree(centralID) {
    $(document).ready(function(){
        $.getJSON('MurakiMaida.json', async_function_1);
}); //document.ready
}

修复将ProcessArray代码移动到第二个异步函数定义的末尾,如下所示:

# Same as above except

var async_function_1 = function(data) {
   $.each(data.person, function(i, xdata) {
   ...create a small set of arrays
   }); //end of first $.each() routine

   $.getJSON('MurakiMaida.json', async_function_2);
} 

var async_function_2 = function(data) {
   $.each(data.person, function(i, xdata) {
   ...use an array just created to create another
   }); //end of second each()
   $("#spchildren").html(ProcessArray(SortArray(childIDs, true), centralID, false));
};