Search Array AS3 Utility Class

September 6th, 2009 No comments »

Here is a class that searches an array for a string. It returns true for a match and false if there is no match.


package {
public class ArraySearcher{
// ------- Properties -------
public var theArray:Array;
public var theTerm:String;
private var match:Boolean;

// ——- Constructor ——-
public function ArraySearcher() {
}

// ——- Methods ——-
function searchArray(theArray:Array,theTerm:String):Boolean{
//set the match variable to false until a match is found
match = false;
for(var i:uint = 0; i < theArray.length; i++){
//trace(”theArray[i] is ” + theArray[i]);
//trace(”TheTerm is ” + theTerm);
if(theTerm == theArray[i]){
//trace(”match”);
match = true;
}
}
//trace(”***end search***”);
return match;
}
}
}

Then in your Main.as document…

import ArraySearcher;
var searcher:ArraySearcher = new ArraySearcher();

searcher.searchArray(someArray,someTerm);

Make sure the someArray is an array and someTerm is cast as a string (for example, if using a term from an XML node). Otherwise, change the parameter in the searchArray function to the type of object you are looking for in your array.