[Solved-5 Solutions] Javascript closure inside loops - javascript tutorial
Problem:
Code:
It outputs this:
We want output like this:
What's the solution to this basic problem ?
Solution 1:
The problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.
Solution 2:
You can try this:
Solution 3:
You can use Function.prototype.bind
The function to be created from outside the loop and then binding the results within the loop.
Solution 4:
Using an Immediately-Invoked Function Expression, the simplest way to readable and enclose an index variable:
Read Also
node.js - While LoopSolution 5:
The scope of the variables in javascript is based on the function. In c# have a block scope, and copying the variable to one inside.