请参见下面的代码。我试图将其剥去裸露的骨头。
See code below. I've tried to strip it to its bare bones.
我有一个_queue数组。我想重复10次。在每次迭代中,我想创建一个具有适当范围的j引用的函数(即,第一次迭代j = 0,第二次迭代j = 1,依此类推)
I have a _queue array. I want to iterate 10 times. On each iteration, I want to create a function that has a properly scoped reference for j (i.e. j=0 on the first iteration, j=1 on the second iteration, etc.)
我想将该函数存储在变量f中,然后将f添加到_queue数组中,以便稍后使用。
I want to store that function in variable f, and then add f to the _queue array so I can call it later.
当然,问题在于在第一个循环的每次迭代中,它没有立即将闭包存储在f中,而是立即执行闭包。
The problem of course is that on each iteration of the first loop, instead of storing the closure in f, it immediately executes the closure.
我的问题是:如何使用适当的j变量存储函数,以便可以将其添加到_queue数组中?
My question is this: How do I store the function with its proper j variable so that I can add it to the _queue array?
_queue = []; for (j = 0; j < 10; j++) { var f = (function (index) { alert(index); })(j); //code is executed here instead of stored in the f variable _queue.push(f); //Add f } for (k = 0; k < _queue.length; k++){ _queue[k].call(); }推荐答案
使用立即函数(或通常使用一个函数)引入一个新的范围是正确的。但是您必须从立即函数中返回一个函数:
Using an immediate function (or in general using a function) to introduce a new scope is correct. But you have to return a function from the immediate function:
var f = (function (index) { return function() { alert(index); }; }(j));更多推荐
如何在循环中创建闭包并将其存储在变量中以供以后执行
发布评论