Back to Vlad
Project 2

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

Sklyarenko Vlad

01 · The array

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

02 · Direct and Shifted

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.

03 · Step by step

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.

index–
item.name–
k–
arr[k].Say()–

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.

04 · Notes

What to remember

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.

Same loop, written differently

Web hosting by Somee.com