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