简体   繁体   English

变量i不会传递给JavaScript中的循环中的函数

[英]variable i is not passed into a function in a loop in JavaScript

I understand there is no block level scope for var i ; 我知道var i没有块级范围; however, in the following code, d.push(); 但是,在下面的代码中,d.push(); is executed after the initialisation of i, why i here remains undefined? 在i初始化之后执行,为什么我在这里仍未定义?

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. 您可以使用.bind()来推送匿名函数的参数绑定版本,从而确保第一个参数的值。

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

Here's my solution: 这是我的解决方案:

var d = [];

function newFunction(i) {
    var k = i; 
    return function() {
        console.log('iterator: ' + k);
    }
}
for (var i = 0; i < 3; i++) {
     d.push(
        newFunction(i)
    );
}
d[0]();
d[1]();

This works because when you create the new function, it creates a variable scope that doesn't change with your for loop. 这是有效的,因为在创建新函数时,它会创建一个不随for循环而变化的变量范围。 It saves the state of i on each iteration so that when you call them again, it runs with the i it was originally declared with. 它会在每次迭代时保存i的状态,这样当你再次调用它时,它会以最初声明的i运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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