Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable i is not passed into a function in a loop in JavaScript

Tags:

javascript

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

like image 996
Xuzheng Wang Avatar asked Apr 03 '26 03:04

Xuzheng Wang


1 Answers

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
like image 96
techfoobar Avatar answered Apr 08 '26 05:04

techfoobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!