闭包之外的解决方法

常见问题:

var fn = [];
function print() {
    for (var i = 0; i < 3; i++) {
        fn[i] = function () {
            console.log(i);
        }
    }
}
print() 

fn.forEach(function (fn) { fn(); })

这样,最后会打印出3次数字3;

 

我们实际上是想依次打印0,1,2。解决方案首先会想到使用闭包:

var fn = [];
function print() {
    for (var i = 0; i < 3; i++) {
        fn[i] = (function (i) {
            return function () {
                console.log(i);
            }
        })(i)
    }
}
print()

fn.forEach(function (fn) {
    fn();
})

 

另外的解决方案:

var fn = [];
function print() {
    for (var i = 0; i < 3; i++) {
        fn[i] = new Function('console.log(' + i + ');');
    }
}
print()

fn.forEach(function (fn) {
    fn();
})

 

或者,可以使用ES6中的新关键字let:

var fn = [];
function print() {
    for (let i = 0; i < 3; i++) {
        fn[i] = function () {
            console.log(i)
        }
    }
}
print()

fn.forEach(function (fn) {
    fn();
})

 

posted on 2017-03-23 18:21  zmiaozzz  阅读(183)  评论(1编辑  收藏  举报

导航