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

why is my array "undefined?"

本文关键字:未定义 我的 数组 为什么      更新时间:2023-09-26

在我一直在使用的主要应用程序中,Stack Overflow大师一直是我的救星,我决定通过将主例程的SortArray分支拆分为它自己的函数来避免我见过的一些异步复杂性。在函数返回结果之前显示完美结果的测试。

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

在下面的代码示例中,我展示了当前结构,这是我对给出的建议的解释(最近由jfriend00给出)。我赚了两美元。getJSON调用,第二个调用在第一个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
}

如果我正确理解了你的代码(一个大的If),这是一个异步处理的问题。第二个Ajax调用的结果函数正在创建"子"数组,对吗?

但是Ajax调用的结果函数直到稍后才被调用。你正在立即调用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代码移到第二个async函数定义的末尾,如下所示:

# 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));
};