javascript闭包在for循环 [英] javascript closure in a for loop
本文介绍了javascript闭包在for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
结果为1,2,3而不是3,3,3。如何设置上下文/范围,使作业使用正确的作用域i?
so I would like the results to be 1,2,3 instead of 3,3,3. How do I set the context/scope so that the jobs are using the correctly scoped "i"?
function buildJobs(list) {
var jobs = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
jobs.push( function() {alert(item)} );
}
return jobs;
}
function testJobs() {
var jobs = buildJobs([1,2,3]);
for (var j = 0; j < jobs.length; j++) {
jobs[j]();
}
}
推荐答案
内部函数与另一个立即执行的函数并接收 i
作为参数:
Wrap the inner function with a another function that's immediately executed and receives i
as an argument:
function buildJobs(list) {
var jobs = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
(function(i) {
jobs.push( function() {alert(list[i])} );
})(i);
}
return jobs;
}
您现在关闭 i
是对包装函数的本地化,这是每次迭代中不同的变量。 (在原始配置中,每个内部函数都在相同的变量(在执行任何函数时其值为
3
)。 )
You're now closing over the i
that is local to the wrapper function, which is a different variable in each iteration. (In your original configuration each inner function was closing over the same variable (whose value was 3
by the time any of the functions ever executed).)
这篇关于javascript闭包在for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文