This question already has answers here:
JavaScript closure inside loops – simple practical example

(44个答案)


5年前关闭。




下面的代码将“K”打印16次。
var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    (function(i){
        fns[rest[i]] = function() {
            console.log(rest[i]);
        };
        fns.K();
    })(i);
}

这段代码打印出所有字母“K”,“L” .......“Y”,“Z”
var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    fns[rest[i]] = function() {
        console.log(rest[i]);
    };
    fns.K();
}

我是JavaScript的新手,并且不太了解第二个示例中IIFE的使用如何导致不同的行为。有人可以澄清一下吗?

最佳答案

var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    (function(i){
        //the i inside this function is private, it is not the same i from outside,
       //Any modification to the i from the loop won't affect this one.
        fns[rest[i]] = function() {
            console.log(rest[i]);
        };
        fns.K();
        // fns[rest[i]](); You should use this if for printing the correct letter
    })(i);
}

没有IIFE
var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    fns[rest[i]] = function() { //You declare a function for each letter
        console.log(rest[i]); //This i contains always the current iteration from the loop
    };
    fns.K(); //calls the first function defined, "K" that prints the current  iteration
}

07-24 09:37
查看更多