0

I work with a array functions. When i try to put into a function, it work wrong. But i put in global, it work correctly. Please help :<, tell me details...

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

i expect output of myArray1[0]() is 0 but actual output is 3

1 Answers1

1

use var instead of let in your second loop. for more detail checkout this article(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
Saad Mehmood
  • 691
  • 1
  • 7
  • 19