search

Home  >  Q&A  >  body text

JavaScript closure problem

**为什么在查找到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]());
滿天的星座滿天的星座2767 days ago489

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-05-19 10:35:04

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:35:04

    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]());

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:35:04

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:35:04

    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

    reply
    0
  • Cancelreply