Callbacks show only the last value from the loop

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 "products." This is because I have console.log in the callback function.

How to save a value in the current iteration?

+4
source share
1 answer

You need to close the loop value if you want to generate functions to run later. This coffee provides the do keyword.

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

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

This is because the body of the loop has a reference to the variable food , which changes the values ​​each time, although the cycle, and when you work, if it finds a closure, the function was created and finds that the food variable is set to the last value of the array. Using another function to create a new area solves the problem.

+10
source

Source: https://habr.com/ru/post/1382401/


All Articles