'Why I put in function, loop does not work properly but in global it's exactly work [duplicate]

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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source