Setting up a array of callbacks and trying to use array index as value in callback

这一生的挚爱 提交于 2019-12-05 10:43:35

Because i is evaluated when the function is called, you'll need to scope that value of i in a new function execution in order to retain the value you expect.

     // returns a function that closes around the `current_i` formal parameter.
var createFunction = function( current_i ) {
    return function( data ) {
        alert( current_i );
    };
};

     // In each iteration, call "createFunction", passing the current value of "i"
     // A function is returned that references the "i" value you passed in.
for (var i = 0; i < 20; i++) {
  callbackDB[i] = createFunction( i );
}

Another solution using an Object.

var callbackDB = new Array();

for (var i = 0; i < 20; i++) {
  callbackDB[i] = {
    value: i,
    callback: function() {
      alert(this.value);
    }
  };
}
			
callbackDB[5].callback();

In this case will be necessary to call to the function (In the example it was called "callback")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!