如何将变量传递给匿名函数

编程入门 行业动态 更新时间:2024-10-28 18:33:57
本文介绍了如何将变量传递给匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想传递变量 setTimeout 函数并对其执行某些操作。当我提醒 i 的值时,它会显示我没想到的数字。我做错了什么?我想要从1到8的日志值。

I want to pass variable setTimeoutfunction and do something with that. When I alert value of i it shows me numbers that i did not expected. What i m doing wrong? I want log values from 1 till 8.

var end=8; for (var i = 1; i < end; i ++) { setTimeout(function (i) { console.log(i); }, 800); }

推荐答案

解决此问题的标准方法是使用工厂函数:

The standard way to solve this is to use a factory function:

var end=8; for (var i = 1; i < end; i ++) { setTimeout(makeResponder(i), 800); } function makeResponder(index) { return function () { console.log(index); }; }

实例 | 来源

在那里,我们致电 makeResponder 在循环中,它返回一个函数,该函数关闭传递给它的参数( index )而不是 i 变量。 (这很重要。如果您刚从匿名函数中删除 i 参数,您的代码将部分工作,但所有函数都会看到我当他们跑时,而不是他们最初安排时;在你的例子中,他们都看到 8 。)

There, we call makeResponder in the loop, and it returns a function that closes over the argument passed into it (index) rather than the i variable. (Which is important. If you just removed the i argument from your anonymous function, your code would partially work, but all of the functions would see the value of i as of when they ran, not when they were initially scheduled; in your example, they'd all see 8.)

更新来自您的评论:

...如果我以这种方式调用它将是正确的 setTimeout(makeResponder(i),i * 800); ?

是的,如果您的目标是让每次通话比最后一次大约晚800毫秒发生,那么工作:

Yes, if your goal is to have each call occur roughly 800ms later than the last one, that will work:

实例 来源

我试过 setTimeout(makeResponder(i),setInterval(i)); function setInterval(index){console.log(index * 800);返回索引* 800; } 但它无法正常工作

您不使用 setInterval 这样,可能根本不想用它。

You don't use setInterval that way, and probably don't want to use it for this at all.

进一步更新:您在下面说过:

我需要先迭代打印8延迟8秒,第二次迭代打印7延迟7秒........打印2延迟2秒...打印0延迟0秒

I need first iteration print 8 delay 8 sec, second iteration print 7 delay 7 sec ........print 2 delay 2 sec ...print 0 delay 0 sec.

你刚才使用第二次超时再次应用上述原则:

You just apply the principles above again, using a second timeout:

var end=8; for (var i = 1; i < end; i ++) { setTimeout(makeResponder(i), i * 800); } function makeResponder(index) { return function () { var thisStart = new Date(); console.log("index = " + index + ", first function triggered"); setTimeout(function() { console.log("index = " + index + ", second function triggered after a further " + (new Date() - thisStart) + "ms delay"); }, index * 1000); }; }

实例 | 来源

我想你现在有了你需要的所有工具。

I think you now have all the tools you need to take this forward.

更多推荐

如何将变量传递给匿名函数

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

发布评论

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

>www.elefans.com

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