.getJSON中的变量显示错误 [英] for variable within .getJSON displayed wrong
本文介绍了.getJSON中的变量显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码(javascript/jQuery)
I have the following code (javascript/jQuery)
$(function(){
for(var i=0;i<3;i++){
$.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data){
console.log(i);
console.log(data);
});
}
});
控制台日志:
3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }
是不是真的,console.log(i);
应该在第一个循环中记录0,在第二个循环中记录1,在第三个循环中记录2?但是总会以某种方式返回3:(
isn't it true, that console.log(i);
should log 0 in the first loop, 1 in the second and 2 in the third? But somehow it always returns 3 :(
推荐答案
尝试一下
$(function(){
for(var i=0;i<3;i++){
(function (index) {
$.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data) {
console.log(index);
console.log(data);
});
})(i)
}
});
这篇关于.getJSON中的变量显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文