Planet JFX

Array Iteration with For

118pages on
this wiki
Add New Page
Add New Page Talk0

Consider the following array of String:

var animal:String* = ["ape", "bear", "cat", "dog"];

When you wish to iterate through such an array and don’t need to know an element’s position, you should use the “list comprehension” version of for:

for (creature in animal)
    System.out.println( creature );

If you need to know an element’s position, you might be tempted to do something like this:

for (i in [0..sizeof animal - 1])
    System.out.println( "Animal {i} - {animal[i]}" );

If the array is not empty, the code works. If, however, you have an empty array, the range expression [0..sizeof animal-1] will generate the sequence [0, -1], which is almost certainly not what you want.

Instead, go back to the original list comprehension form, and let the indexof operator tell you the element’s position:

for (creature in animal)
    System.out.println("Animal {indexof creature} - {creature}");

Also on Fandom

Random Wiki