Array of functions in javascript: cannot understand the results

I cannot understand the result provided by an array of functions in javascript

 var myArray = [];
 for (var i=0;i<5;i++){
     myArray.push(function(a){
        return i+a;
     })           
 }

 alert(myArray[0](2));
 alert(myArray[1](2));

      

I get 7 in the result for both, as if the value i for each function in the array was 5. Could you help me understand this?

+3
javascript


source to share


No one has answered this question yet

See similar questions:

2660
Closing JavaScript Inner Loops - A Simple Practical Example

or similar:

7649
How does JavaScript blocking work?
7494
How can I remove a specific element from an array in JavaScript?
7432
How to check if a string contains a substring in JavaScript?
7287
What does "use strict" do in JavaScript, and what are the reasons for it?
6493
var functionName = function () {} vs function functionName () {}
5670
Which operator is equal (== vs ===) should be used in JavaScript comparisons?
4829
How do I include a JavaScript file in another JavaScript file?
4380
For each by an array in JavaScript?
2256
Set default parameter value for JavaScript function
1489
How can I loop through a simple JavaScript object with objects as members?



All Articles
Loading...
X
Show
Funny
Dev
Pics