example needed of callback function inside for loo

2019-08-05 03:11发布

I'm looking for something simple and straight forward, most of what I've pulled up on stack isn't quite what I need. I have an array that I want to loop through while calling a function after each iteration. What would that look like?

3条回答
仙女界的扛把子
2楼-- · 2019-08-05 03:44

I'm assuming you're having problems with this because of the way closures are handled in Javascript. Douglas Crockford talks about this, in his book, by using the example of a function that assigns a click event handler to an array of nodes. The "intuitive" way is:

var addHandlers=function(nodes){
    var i;
    for(i=0; i<nodes.length;++i){
        nodes[i].onClick= function {
            alert (i);
        };
    }
};

However, this is not correct: each onClick callback will show the same value of i = nodes.length-1. This is because the value of i is not copied, but referenced in each inner function. The better way would be to create a helper function that returns a callback, something along the lines of the following:

var addHandlers = function (nodes) {
    var helper = function (i){
        return function (e){
            alert (i);
        }
    }
    for (int i =0; i<nodes.length();i++){
        nodes [i].onClick=helper (i);
    }
}

Plus, this allows you to avoid creating a function at each iteration.

查看更多
放我归山
3楼-- · 2019-08-05 04:02
var arr = [1,2,3];
for(var i = 0; i < arr.length; i++){
  someFunction();
} 
查看更多
一纸荒年 Trace。
4楼-- · 2019-08-05 04:04

If you want to process one elment of the array to be used in an asynchronous funcion and then process the next next element you can do something like this;

function asynchCallback(arrayToProcess,someVar){
  console.log("callback called with parameter:",someVar);
  processArray(arrayToProcess);
}

function processArray(arr){
  if(arr.length===0){
    console.log("done");
    return;
  }
  var someVar=tmp.splice(0,1);
  setTimeout(function(){
    asynchCallback(tmp,someVar[0]);
  },100);
}
//send a copy of the array:
processArray([1,2,3].concat());
查看更多
登录 后发表回答