问题
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);
});
}
});
console log:
3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }
3
Object { stream: Object, _links: Object }
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 :(
回答1:
Try this
$(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)
}
});
回答2:
If you are using ecma6 then you can use let to avoid closure issue. It create block scoping.
$(function() {
for (let i = 0; i < 3; i++) {
$.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data) {
console.log(i);
console.log(data);
});
}
});
otherwise,You can use IIFE
$(function() {
for (var i = 0; i < 3; i++) {
(function(i) {
$.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data) {
console.log(i);
console.log(data);
});
})(i)
}
});
Similary,you can use bind.
回答3:
Can you display result in $.getJson success?
$(function(){
$.getJSON("https://api.twitch.tv/kraken/streams/esl_csgo", function(data){
for(var i=0;i<3;i++){
console.log(i);
console.log(data[i]);
}
});
});
Your i=3 because your loop does not wait $.getJson success. It is working and increment values without delay.
回答4:
Try This
$.ajaxSetup({
async: false
});
$(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);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/38944850/for-variable-within-getjson-displayed-wrong