设置一个回调数组并尝试在回调中使用数组索引作为值

Xav*_*ier 5 javascript function-pointers callback

当我以这种方式设置一个回调数组时,我在对话窗口中得到20个所有回调.我想在数组中获取索引.这可能吗?调用回调的函数期望回调具有一个参数.我不控制回调的调用者,因为它是外部库的一部分.任何帮助表示赞赏.

for (var i = 0; i < 20; i++) {
  callbackDB[i] = function(data) {
    alert(i);
  }
}
Run Code Online (Sandbox Code Playgroud)

use*_*716 11

因为i在调用函数时会对其进行求值,所以您需要i在新函数执行中调整该值的范围,以便保留您期望的值.

     // 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 );
}
Run Code Online (Sandbox Code Playgroud)