回调只能看到循环中的最后一个值

发布于 2024-12-17 11:16:29 字数 183 浏览 1 评论 0原文

我有这样的代码:

for food in foods
  Person.eat ->
    console.log food

这里的问题是“食物”永远是“食物”中的最后一个“食物”。那是因为我在回调函数中有 console.log 。

如何保留当前迭代中的值?

I have this code:

for food in foods
  Person.eat ->
    console.log food

The problem here is that "food" will always be the last "food" in "foods". That is because I have the console.log in a callback function.

How can I preserve the value in the current iteration?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沧笙踏歌 2024-12-24 11:16:29

如果您想生成稍后运行的函数,则需要关闭循环的值。这就是 Coffee 提供 do 关键字的目的。

for food in foods
  do (food) ->
    Person.eat ->
      console.log food

看这个例子:
https://gist.github.com/c8329fdec424de9c57ca

发生这种情况是因为您的循环体引用了 food 变量每次通过循环都会更改值,当您运行 if 时,会发现创建该函数的闭包,并发现 food 变量设置为数组的最后一个值。使用另一个函数来创建新范围可以解决该问题。

You need to close over the value of a loop if you want to geneate functions to run later. This what coffee provides the do keyword for.

for food in foods
  do (food) ->
    Person.eat ->
      console.log food

See this example:
https://gist.github.com/c8329fdec424de9c57ca

This occurs because your loop body has a reference to the food variable which changes values each time though the loop, and when you function if finds the closure the function was created in and finds that food variable set to the last value of the array. Using another function to in order to create a new scope solves the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文