这是您的闭包中的 i 的问题,当调用 this.api.stalk 的回调时,可能 i 是 mods.length。请参见以下示例:
var i = 0;
var arr=["hi","there"];
for(i=0;i<arr.length;i++){
setTimeout(function(){
console.log(arr[i]); //undefined
console.log("and i is:"+i); //i will be 2
},100);
}
以下是解决闭包问题的方法:
var i = 0;
var arr=["hi","there"];
for(i=0;i<arr.length;i++){
setTimeout(
(function(index){
return function(){
console.log("Index is:"+index);//0 and 1
console.log("arr at index:"+arr[index]);//hi and there
console.log("i is:"+i);//2 and 2
console.log("arr at i:"+arr[i]);//undefined and undefined
}
})(i)
,100);
}
您的代码可能类似于:
var mods = this.registry.gmmods;
for (var i = 0; i < mods.length; i++) {
if(mods[i] != this.config.botid){
this.api.stalk(mods[i],true,
(function(index){
return function (data){
console.log("index is:"+index);
console.log(mods[index]);
console.log("i is:"+i);
console.log(mods[i]);
}
})(i)
);
}
}