Loops with forEach
One array, four animals, two ways to walk through it. Click, add your own animal, and step through the loop one turn at a time.
Sklyarenko Vlad
Four objects in an array
Each animal is an object with a name and a method Say(). The array holds them in order. Click an animal to hear it. You can add your own or remove one, and every demo below uses the array you build.
The code
Two buttons, one operator
Direct: every animal says its own sound. Shifted: every animal says what the next animal says, and the last one wraps around to the first.
In the lecture, arr is re-created inside each function. Here it is created once, in section 01, so the animals you add stay in the array. The unused var k = 0 in Second() is left out.
Watch forEach take its turns
forEach calls your function once per element, in order. Press Step to run one turn and see the values it hands over: item, index and the array itself.
Pink is item, the element the loop is on. The lime ring is arr[k], the animal whose sound gets printed. In Direct mode they are the same animal. In Shifted mode k is one step ahead, and after the last element it jumps back to 0.
What to remember
- One call per element
arr.forEach(Go)runsGoonce for every element, from the first to the last, in order. - Up to three arguments
The function receives
item(the element),index(its position) andarr(the whole array). - No return value
forEachonly does work, such as printing. To build a new array, usemap.
The wrap-around trick
To point at the next element and loop back after the last one, the lecture uses a conditional (ternary) expression. A shorter way to say the same thing is the remainder operator.