Thursday, September 2, 2010

Retreiving the Index Value of an Item in an Array in Flash AS3

In AS3, you can retrieve the index value of an item in an array by using the indexOf() method of the Array class. Let's take a look at an example:
var aPets:Array = new Array("dog", "cat" , "hamster", "turtle");
This creates an array named aPets, which is populated with 4 values: "dog", "cat" , "hamster", "turtle". Just by looking at the order in which the values were passed to the array constructor, we know that "dog" has an index of 0, "cat" has an index of 1, and so on... If we wish to retrieve an item's index value within our code, then we can use the indexOf() method of the Array class. For example:
To use the indexOf() method, you pass to it the array item whose index value you would like to retrieve. Flash will then go inside the array and look for that item and retrieve its index value. In the example above, "hamster" is the 3rd item in the array, so the trace statement will output a value of 2.

If an item is not found in the array, a value of -1 is returned. For example:
We did not put a "skunk" item inside the array so Flash won't be able to find said item. Therefore, a value of -1 will be returned.

But what if we had two identical items in the array. Let's say our aPets array had 2 "cat" items instead:
var aPets:Array = new Array("dog", "cat" , "hamster", "turtle", "cat");
Looking at the order in which the values were passed, we see that the first "cat" has an index of 1, and the next "cat" has an index of 4. If we use aPets.indexOf("cats") , Flash will return a value of 1, because that is the index value of the first "cat" that it will find in the array. What happens is that Flash will start looking from the index of 0, and then once it finds the item, it returns the index value and stops looking, regardless of whether or not there might be another identical item within the array.

So what if we wanted to skip the first "cat" and try to retrieve the index value of the other one that has a higher index?
Well, then we can tell Flash to start counting at a higher index value than that of the first "cat" (instead of starting at 0, which is the default). To do that, we simply pass a second parameter to the indexOf() method. That second parameter is called the fromIndex parameter of the indexOf() method. It tells Flash at which index number it should begin searching for the specified item. For example:
trace(aPets.indexOf("cat", 2));
Here, we've passed a value of 2 to the fromIndex parameter. This means that when Flash begins searching through the array, it will start from the index of 2, skipping the items with a lower index value. And since the first "cat" has an index value that is lower than 2, then it won't be included in the search. The "cat" that will be found, then, will be the other one that has the index value of 4.