回调只能看到循环中的最后一个值
我有这样的代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想生成稍后运行的函数,则需要关闭循环的值。这就是 Coffee 提供
do
关键字的目的。看这个例子:
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.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.