Javascript: closing a loop?

I would like to do something like the following:

for(var i = 0; i < 10; ++i) { createButton(x, y, function() { alert("button " + i + " pressed"); } } 

In this, I always get the final value of i , because closing the Javasript is not a value.
So how can I do this with javascript?

+5
javascript closures anonymous-function
source share
5 answers
 for(var i = 0; i < 10; i++) { (function(i) { createButton(function() { alert("button " + i + " pressed"); }); })(i); } 

Please note that JSLint does not like this template. It throws "Do not perform functions inside a loop."

Live demo: http://jsfiddle.net/simevidas/ZKeXX/

+6
source share

One solution, if you are encoding a browser that uses JavaScript 1.7 or higher, is to use the let keyword:

 for(var i = 0; i < 10; ++i) { let index = i; createButton(x, y, function() { alert("button " + index + " pressed"); } } 

At the MDC Document Center:

The let keyword invokes the element variable created by the level block, invoking a new link for each iteration of the for loop. This means that a separate variable is fixed for each closure, a solution to the problem caused by the general environment.

Check out the MDC Doc Center for a traditional approach (create another closure).

+7
source share

Create a new area to close by executing another function:

 for(var i = 0; i < 10; ++i) { createButton(x,y, function(value) { return function() { alert(...); }; }(i)); } 

http://www.mennovanslooten.nl/blog/post/62

+4
source share

You need to put the closure in a separate function.

 for(var dontUse = 0; dontUse < 10; ++dontUse) { (function(i) { createButton(x, y, function() { alert("button " + i + " pressed"); } })(dontUse); } 

This code creates an anonymous function that takes i as a parameter for each iteration of the loop.
Since this anonymous function has a separate parameter i for each iteration, it fixes the problem.

It is equivalent

 function createIndexedButton(i) { createButton(x, y, function() { alert("button " + i + " pressed"); } } for(var i = 0; i < 10; ++i) { createIndexedButton(i); } 
+1
source share
 for(var i = 0; i < 10; ++i) { createButton(x, y, (function(n) { return function() { alert("button " + n + " pressed"); } }(i)); } 

An anonymous function from the outside is automatically called and creates a new closure with n in its area, where with each call it takes the current value i .

0
source share

All Articles