【问题标题】:How do I modify my array in the callback function?如何在回调函数中修改我的数组?
【发布时间】:2015-11-13 15:41:31
【问题描述】:

我对 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

【问题讨论】:

  • 你不需要传递newArray你可以通过闭包在回调函数中访问。
  • 假设我的 someclass.functionThatWillPerformAjax() 存在于另一个文件中?
  • 我想我们需要查看someclass.functionThatWillPerformAjax 的代码才能给你一个很好的指示。
  • 我会说让你的“回调”函数包装在一个实际的 ajax 成功回调函数中,并将你的新数组传递给你当前调用回调函数的函数。
  • "once all calls are done" — 当所有 Ajax 请求 sent 时,该代码行将运行,not 当它们有 完成

标签: javascript ajax callback


【解决方案1】:

你可以这样做:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2014-04-06
    • 2021-06-26
    • 1970-01-01
    • 2014-04-21
    • 2011-09-29
    • 2021-09-18
    相关资源
    最近更新 更多