I understand there is no block level scope for var i ; however, in the following code, d.push(); is executed after the initialisation of i, why i here remains undefined?
var d = [];
for (var i = 0; i < 3; i++) {
d.push(function(i) {
console.log('iterator: ' + i);
});
}
d[0]();//undefined
Any thoughts will be appreciated
You can push an argument-bound version of the anonymous function by using .bind() thereby ensuring the value of the first argument.
var d = [];
for (var i = 0; i < 3; i++) {
d.push((function(i) {
console.log('iterator: ' + i);
}).bind(this, i));
}
d[0](); // iterator: 0
d[1](); // iterator: 1
d[2](); // iterator: 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With