Wednesday, August 25, 2010

Working with Arrays in AS3: Part 2

In this tutorial we will learn how to gain access to every Array element using loop and how to find elements that match a specific criteria.

From the previous tutorial we have learned about Array.length property, which returns the total number of all elements in the Array. The length of an Array is always greater than the last element's index - index counting starts from 0, while element count - from 1.

In this example we trace the values of each element in the Array:

var myArray = ["one","two","three"];
for (var i:int=0; i < myArray.length; i++){
trace("Element with the index of " + i + " has a value of " + myArray[i]);
}

We can also do the same thing, but start taking the elements from the end to beginning. The starting value of i should be the last element's index (length - 1). Condition should be i>=0 and with each loop the value of i should decrease:

var myArray = ["one","two","three"];
for (var i:int=myArray.length - 1; i >=0 ; i--){
trace("Element with the index of " + i + " has a value of " + myArray[i]);
}

Sometimes it is needed to return elements that match a specific criteria. In the next example, we trace all element indexes that have a value of "two".

var myArray = ["one","two","three","one","two","three"];
var matchValue:String = "two"
for (var i:int=0; i < myArray.length; i++){
if(myArray[i] == matchValue){
trace("Element with the index of " + i + " matches " + matchValue);
}
}

What if we only want to find one match? Simply use the break statement. Break stops the loop from going further, which is useful, because it saves computing time. Of course, we wouldn't even notice the difference, because we only have 6 elements. But what if we have 1000?

Here's an example:

var myArray = ["one","two","three","one","two","three"];
var matchValue:String = "two"
for (var i:int=0; i < myArray.length; i++){
if(myArray[i] == matchValue){
trace("Element with the index of " + i + " matches " + matchValue);
break;
}
}

You can also start the search from the end:

var myArray = ["one","two","three","one","two","three"];
var matchValue:String = "two"
for (var i:int=myArray.length - 1; i >=0 ; i--){
if(myArray[i] == matchValue){
trace("Element with the index of " + i + " matches " + matchValue);
break;
}
}

Thanks for reading!

Related:

Working with Arrays in AS3: Part 1
Working with Arrays in AS3: Part 3
Working with Arrays in AS3: Part 4
Working with Arrays in AS3: Part 5
Working with Arrays in AS3: Part 6
Working with Arrays in AS3: Part 7

No comments:

Post a Comment