Created
December 11, 2014 11:48
-
-
Save crudbetter/09d042d486e1a1b39a91 to your computer and use it in GitHub Desktop.
JavaScript closure of iterator index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var foos = [ | |
{ bar: 1 }, | |
{ bar: 2 } | |
]; | |
for (var i = 0; i < foos.length; i++) (function(index) { | |
setTimeout(function() { | |
console.log(foos[index].bar); | |
}, 1); | |
})(i); | |
// rather than | |
for (var j = 0; j < foos.length; j++) { | |
setTimeout(function() { | |
console.log(foos[j].bar); | |
}, 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment