I'm looking for something simple and straight forward, most of what I've pulled up on stack isn't quite what I need. I have an array that I want to loop through while calling a function after each iteration. What would that look like?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I'm assuming you're having problems with this because of the way closures are handled in Javascript. Douglas Crockford talks about this, in his book, by using the example of a function that assigns a click event handler to an array of nodes. The "intuitive" way is:
However, this is not correct: each onClick callback will show the same value of
i = nodes.length-1
. This is because the value ofi
is not copied, but referenced in each inner function. The better way would be to create a helper function that returns a callback, something along the lines of the following:Plus, this allows you to avoid creating a function at each iteration.
If you want to process one elment of the array to be used in an asynchronous funcion and then process the next next element you can do something like this;