这就是我所拥有的
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 (data){
console.log(mods[i]);
});
}
}
只有控制台日志输出未定义,我似乎可以弄清楚如何在回调函数中获取该数据,因为回调数据不包含它
任何人都可以告诉我如何能够做到这一点
答案 0 :(得分:3)
这是关闭i的问题,当调用this.api.stalk的回调时,机会是我是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)
);
}
}