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

标签 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

最佳答案

你可以这样做:

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

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

关于javascript - 如何在回调函数中修改数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33696438/

相关文章:

javascript - 使用 GET 请求获取详细信息时,返回 401 错误

javascript - MVC Razor 共享布局页面渲染问题

php - 如何从 php javascript 中获取值?

javascript - 在 ASP MVC 5 中使用 AJAX 时,HttpPostedFileBase 为空

javascript - Jasmine 节点不等待主体完成

javascript - 来自服务器 json 对象的数据表

javascript - JQuery从ajax加载中获取元素id数据

java - 回调和 dto 之间有什么关系?

facebook - 应用程序设置编辑器中的连接 URL

javascript - Vanilla JS - 单击元素后执行代码