如何获取数组中的最后一个元素?是否需要使用JavaScript闭包?

4
我有一个函数,它循环遍历一个多维数组,该数组由我网页上一个区域的ID和我要传递到Web服务的参数组成。从$.ajax()调用返回的内容将是HTML,我希望在数组的第一部分中填充(重绘)该内容:
function getViews(){

    // loop through, need view/jsp name and where we want to put the HTML... need a multidimarray...
    var viewArr = [["infoCol","info"], 
                   ["noteCol", "notes"],
                   ["buttonsDiv", "buttons"],
                   ["historyPanel","history"], 
                   ["servicesPanel","services"],
                   ["noFOUC","dialogs"]
                  ];

    // do the loop
    for(var i = 0;i<viewArr.length;i++){

        var thisArea = viewArr[i][0];

        $.ajax({
            url:"getView",
            type:"POST",
            data:{view:viewArr[i][1]},
            dataType:"html",
            success:function(data){
              console.log(thisArea); // this is always noFOUC
              // console.log(viewArr[i][0]); // this gives an undefined error...
                $("#" + thisArea).html(data);
            },
            error:function(xhr, ajaxOptions, thrownError){
                console.log(xhr.status);
                console.log(xhr.statusText);
                console.log(thrownError);
            }
        }); 

    }
}

现在一切都很好,然而尝试在success回调函数中引用循环的第一部分viewArr[i][0]却不起作用!如果我将它放在success中,它是未定义的。如果我在$.ajax()外面给它一个变量,就像上面的例子一样,它总是数组的最后一项!我确定我需要在这里添加闭包,但不知道为什么要添加以及在哪里添加,请问有人能解释一下吗?如果我没有表述清楚,请让我知道,我会解释得更好。

欢迎来到“异步”世界。 - kidwon
1个回答

3

我想我有这个问题......我在循环内部放置了一个自执行函数...忘记了异步!循环继续... 糟糕!

function getViews(){

    // loop through, need view/jsp name and where we want to put the HTML... need a multidimarray...
    var viewArr = [["infoCol","info"], 
                   ["noteCol", "notes"],
                   ["buttonsDiv", "buttons"],
                   ["historyPanel","history"], 
                   ["servicesPanel","services"],
                   ["noFOUC","dialogs"]
                  ];

    // do the loop
    for(var i = 0;i<viewArr.length;i++){

        (function(){

        var thisArea = viewArr[i][0];
        $.ajax({
            url:"getView",
            type:"POST",
            data:{view:viewArr[i][1]},
            dataType:"html",
            success:function(data){
                $("#" + thisArea).html(data);
            },
            error:function(xhr, ajaxOptions, thrownError){
                console.log(xhr.status);
                console.log(xhr.statusText);
                console.log(thrownError);
            }
        }); 

        })(viewArr[i][0]);

    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接