This question already has answers here:
JavaScript closure inside loops – simple practical example
                            
                                (44个答案)
                            
                    
                    
                        How do JavaScript closures work?
                            
                                (86个答案)
                            
                    
                    
                        What's the difference between using “let” and “var”?
                            
                                (34个答案)
                            
                    
                去年关闭。
        

    

我使用数组函数。当我尝试放入一个函数时,它会出错。但是我输入全局,它可以正常工作。请帮助:
function a(){
    var arr = [];
    for(var i=0;i<3;i++){
        arr[i] = function(){
            console.log(i);
        }
    }
    return arr;
}
var myArray1 = a();

myArray1[0]();
/// 3

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

myArray2[0]();
/// 0


我希望myArray1[0]()的输出为0,但实际输出为3

最佳答案

用户var而不是第二个循环中的let。有关更多详细信息,请查阅本文(https://medium.com/front-end-developers/es6-variable-scopes-in-loops-with-closure-9cde7a198744)。



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

myArray1[0]();
/// 3

var myArray2 = [];
for(var i=0;i<3;i++){ // user var instead of let here
    myArray2[i]=function(){
        console.log(i);
    }
}

myArray2[0]();
/// 3

关于javascript - 为什么我放入函数,循环无法正常工作,但在全局范围内却可以正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54494148/

10-12 06:33