如何在循环中创建闭包并将其存储在变量中以供以后执行

编程入门 行业动态 更新时间:2024-10-28 02:24:55
本文介绍了如何在循环中创建闭包并将其存储在变量中以供以后执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请参见下面的代码。我试图将其剥去裸露的骨头。

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));

更多推荐

如何在循环中创建闭包并将其存储在变量中以供以后执行

本文发布于:2023-07-14 22:19:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1107338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   以供   如何在   并将其

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!