最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Setting up a array of callbacks and trying to use array index as value in callback - Stack Overflow

programmeradmin3浏览0评论

When I setup an array of callbacks this way I get 20 in the dialog window for all callbacks. I'd like to get the index in the array instead. Is this possible? The function that calls the callback is expecting the callback to have one parameter. I don't control the caller of the callback because it is part of an external library. Any help is appreciated.

for (var i = 0; i < 20; i++) {
  callbackDB[i] = function(data) {
    alert(i);
  }
}

When I setup an array of callbacks this way I get 20 in the dialog window for all callbacks. I'd like to get the index in the array instead. Is this possible? The function that calls the callback is expecting the callback to have one parameter. I don't control the caller of the callback because it is part of an external library. Any help is appreciated.

for (var i = 0; i < 20; i++) {
  callbackDB[i] = function(data) {
    alert(i);
  }
}
Share Improve this question asked Jan 23, 2011 at 1:31 XavierXavier 9,04916 gold badges69 silver badges100 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

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")

发布评论

评论列表(0)

  1. 暂无评论