|
|
|
|
|
by Izkata
936 days ago
|
|
It was also a rarely-used classic way to deal with variable references that changed in a loop: var values = [];
for (var i = 0; i < 3; i++) {
values.push(function() { console.log(i); });
}
for (var j = 0; j < 3; j++) {
values[j]();
}
This would log 3, 3 times. The usual fix (before the variety of modern ways) was to use an IIFE in the first loop: for (var i = 0; i < 3; i++) {
(function(i) {
values.push(function() { console.log(i); });
})(i);
}
Alternatively, this works: for (var i = 0; i < 3; i++) {
with ({i: i}) {
values.push(function() { console.log(i); });
}
}
|
|