JavaScript closure problem
滿天的星座
滿天的星座 2017-05-19 10:33:04
0
4
452
**为什么在查找到i的时候i变成了3;**

function outer(){
            for (var i = 0,arr=[];i<3;i++){
                arr[i] = function(){
                    return i;
                }                            
            }
            return arr;
        }
        var getNum = outer();
        console.log(getNum[0](),getNum[1](),getNum[2]());
滿天的星座
滿天的星座

reply all(4)
刘奇

Because your anonymous function function(){return i;} is not executed, i here is undefined, and then return arr, this is function(){return i;} stored in the array. When you getNum[0]( ) is when the above for (var i = 0, arr=[];i<3;i++){} is executed, i=3; so getNum[0](),getNum[1](),getNum[2 ]() outputs all 3.

Ty80

That’s right now. The closure problem is solved in the same way

function outer(){
            for (var i = 0,arr=[];i<3;i++){
                arr[i] = (function(index){
                    return function() {
                        console.log(index)
                    };
                })(i)                   
            }
            return arr;
        }
        var getNum = outer();
        console.log(getNum[0](),getNum[1](),getNum[2]());
小葫芦

Because i is a peripheral variable, it is only found when calling.
And when you call it, the loop has ended and the value of i is already 3, so you can only get 3

洪涛
function outer(){
    for (let i = 0,arr=[];i<3;i++){
        arr[i] = function(){
            return i;
        }                            
    }
    return arr;
}
var getNum = outer();
console.log(getNum[0](),getNum[1](),getNum[2]());

Problem of defining domain

var changed to let

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!