for variable within .getJSON displayed wrong [duplicate]

假装没事ソ 提交于 2020-01-07 02:33:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!