Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: closure of loop?

I would like to do the something along the following:

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

The problem with this is that I always get the final value of i because Javascript's closure is not by-value.
So how can I do this with javascript?

like image 779
shoosh Avatar asked Apr 05 '11 16:04

shoosh


1 Answers

One solution, if you're coding for 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"); }
}

From the MDC Doc Center:

The let keyword causes the item variable to be created with block level scope, causing a new reference to be created for each iteration of the for loop. This means that a separate variable is captured for each closure, solving the problem caused by the shared environment.

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

like image 162
McStretch Avatar answered Nov 15 '22 00:11

McStretch