简体   繁体   中英

`jQuery.getJSON()` function inside a for loop

I have the following code which returns h=30 instead of each value inside the loop.

for (var h = 0; h < 31; h++) {
  $.getJSON('http://google.com/',
    function(data) {
      console.log('line ' + h);
    }
  )
};

What do I need to do to get loop values?

Make a closure with an IIFE

for (var h = 0; h < 31; h++) {
    (function(h) {
        $.getJSON('http://google.com/', function(data) {......
            console.log('line ' + h);
        })
    })(h)
};

That way, the value of h will be preserved for that iteration instead of being set to the last value by the time getJSON is called back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM