Game Development Reference
In-Depth Information
sort the list by their
positions from left to right. The code would
probably look something like the following:
enemyList.sortOn( " x " );
There are also special constants built into the Array class that
allow you to specify sorting order. By default, Arrays will sort in
ascending order, that is, from smallest to largest. You can add a
second parameter to the sortOn method to specify a different order.
enemyList.sortOn( " x " , Array.DESCENDING);
For all this flexibility in ordering, Arrays are not without their
shortcomings. Unlike the Object example where we were able to
pinpoint an item in the list based on its name, there is no safe way
to do that with Arrays. You could theoretically store each item
index in the Array in the item itself, but that would assume that the
Array order would never change at all
a largely unsafe assumption
to make. In order to find an item in an Array, you must iterate
through it, compare each item to the one you
re looking up, and
break out of the Array once you
ve found it to minimize processing
protected function enemyClicked(e:MouseEvent) {
var enemy:Sprite = as Sprite;
for (var i:int = 0; i < enemyList.length; i++) {
if (enemyList[i] == enemy) {
enemyList.splice(i, 1);
The larger the Array is, the longer this process takes, and it is
obviously a way less efficient than simply keying off a value like in
an Object. AS3 added two methods that simplify the coding of this
considerably: indexOf and lastIndexOf . These two methods basically
do the search for you, simplifying your code to
protected function enemyClicked(e:MouseEvent) {
var enemy:Sprite = as Sprite;
var index:int = enemyList.indexOf(enemy);
enemyList.splice(index, 1);
The lastIndexOf method does exactly the same search but starts
at the end of the Array and counts down. While this is definitely
less to type and is cleaner than a for loop,theunderlyingprocess
is still the same and large arrays are still taxing on Flash.
Pros: Ordered, lots of sorting options, ease of combining Arrays
Cons: Slower to access specific items (requires iteration), slightly
slower to iterate through than objects
Search Nedrilad ::

Custom Search