I am trying learn Node.js. I dynamically built an array, I used push to put a function in each element.
var arr=[];
for(var x=0;x<8;x++)
arr.push(function(){ console.log(x); });
I 'think' I am pushing a anonymous function into the array that when called should print to the console the value of 'x' during the iteration. IE first iteration x==0, second x==1 and so forth until 8th iteration, this means the largest number pushed should be 7. I then attempt to print each element to the console using a forEach loop
arr.forEach(function(ar)
{
ar();
});
I 'think' this loop will iterate from element [0] to the end of the array. In each iteration I call the function for that element. ar();
I thought I would get the numbers 0,1,2,3... 7 printed to the console, each number on a new line.
For each iteration the number 8 is printed to a new line of the console.
The number 8 shouldn't it be 7? Why is only 8 being printed? What is happening?
If I do not push a function into the array but push x and use a forEach loop to console.log the correct numbers are printed.