Iterating over sequences using for each
When we have a sequence of things, we often want to go through it item by item. We can, of course, do that using a for
loop, like this:
names = ["Anna", "Bob", "Carl", "Danielle"] for i = 0 to names.length print "Hi " + names[i] end_for
On the first line, we declare an array of strings containing some names. We are using a variable called names
to store the values.
Then, we use a for
loop, starting at 0
. To find out how many times we will iterate, we ask the array how many items it currently has stored. We do that by using the names
variable, and, by using a dot, we can get what is known as a property from the array. This property is a value that stores how many items the array currently has. The way we can ask a sequence how many items it has will differ from language to language, but it will most likely be something like what we have done.
We need to remember...