arr = [1,2,3]; arr.forEach(function(i){ // last iteration });
How to catch when the loop ending? I can do if(i == 3)
but I might don't know what is the number of my array.
Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.
The last value is still available after the loop, so if you just want to use it for more stuff after the loop this is better: foreach($arr as $key=>$value) { //something } echo "last index! $key => $value"; If you do not want to treat the last value as special inside loops.
Because forEach does not wait for each promise to resolve, all the prizes are awarded in parallel, not serial (one by one). So the loop actually finishes iterating before any of the prizes have finished been awarded (but after they have all started being awarded).
Updated answer for ES6+ is here.
arr = [1, 2, 3]; arr.forEach(function(i, idx, array){ if (idx === array.length - 1){ console.log("Last callback call at index " + idx + " with value " + i ); } });
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With