How to make anonymous functions with local parameters
How do I make this javascript alert 0, 1 and 2 instead of 3 3's?
var vals = [1, 2, 3];
for(var i = 0; i < vals.length; i++)
{
window.setTimeout(function() {alert(i);}, 1000);
}
I know the reason why it does this, but I can't figure out, how t开发者_JAVA百科o pass i
to the anonymous function.
You can wrap this in a closure like so:
var vals = [1, 2, 3];
for(var i = 0; i < vals.length; i++) {
(function(num) {
window.setTimeout(function() {alert(vals[num]);}, 1000);
})(i);
}
Try it: http://jsfiddle.net/qgL7h/
var vals = [1, 2, 3];
function makeCallback(i)
{
return function () {alert(i);};
}
for(var i = 0; i < vals.length; i++)
{
window.setTimeout(makeCallback(i), 1000);
}
It is not strictly necessary to pass i to the function, it can be assigned to a local var inside.
var vals = [1, 2, 3];
for(var i = 0; i < vals.length; i++) {
(function() {
var num = i
window.setTimeout(function() {alert(vals[num]);}, 1000);
})();
}
The "function(){block}()" was required, because Javascript didn't have proper block lexical variables. Recent editions have added "let", which makes this possible:
var vals = [1, 2, 3];
for(var i = 0; i < vals.length; i++) {
let num = i
window.setTimeout(function() {alert(vals[num]);}, 1000);
}
精彩评论