如何在回调函数中修改数组?

时间:2015-11-13 15:41:32

标签: javascript ajax callback

我是javascript的新手,并试图弄清楚如何在回调发送到另一个函数的调用者数组中添加值。

基本代码是:

var newArray = new Array();
var oldArray = new Array();
oldArray.push(1);
oldArray.push(2);
oldArray.push(3)

for (var value in oldArray) {
  someclass.functionThatWillPerformAjax(oldArray[value], function() {
     // I am trying to figure out how to pass newArray in this callback
     // so that when we receive the response from AJAX request,
     // the value returned from the response pushed to a newArray
  }
}

// once all calls are done, I have my newArray populated with values returned from server

1 个答案:

答案 0 :(得分:0)

你可以这样做:

var newArray = new Array();
var oldArray = new Array();
oldArray.push(1);
oldArray.push(2);
oldArray.push(3);

var someclass.doAjax = function(element, callback) {
  // perform ajax request
  callback(AjaxRequestResult); // send the result of the ajax request in the callback function
};

oldArray.forEach(function (element) { // for each element in oldArray
  someclass.doAjax(element, function(doAjaxResult) { // perform doAjax function
    newArray.push(doAjaxResult); // push the callback's result into newArray
  });
});

但您必须知道,在这种情况下,您的请求可能不会按照调用它们的顺序返回。