Coming from PHP background, or from any other language, one really misses the basic functions which are not available yet in AS3. Flash AS3 has dearth of functions and Array functions are no exception.
This Flash AS3 function will search the provided array and, if found, returns the index of matching item, otherwise returns 0 to use the first item as selected item.
I have added comments with the following code to explain it in details:
function getArrayIndex(myArray, myValue):int { trace("searching for: "+myValue+" array length: "+myArray.length); for (var i=0; i < myArray.length;i++){ if (myValue == myArray[i]) { trace("Found selected item "+myValue+" at array index: "+i); return i; break; } } return -1; } //Let's define array of menu items to be searched var menus:Array = ("Front", "Right", "Back", "Left", "Top"); //item to search in array var selected:String = "Left"; //call the function and, if found, it will return index of the selected item //that you can easily use in the scrollPane or ComboBox components. getArrayIndex(menus, selected);
Hope that helps.
Cheers!
Ali,
I’m sure you are aware by now of the indexOf() method for Arrays, but just in case you or anyone else who stumbles on this post like I did doesn’t know about it, the native indexOf() method will do the exact same thing your getArrayIndex() function does, except that it returns -1 if the item is not found, which is better because you don’t want to use 0 unless the first index is indeed the matching item.
Here is your example condensed into 4 lines (though it could easily be just 2 lines) using indexOf() instead:
var menus:Array = new Array(“Front”, “Right”, “Back”, “Left”, “Top”);
var selected:String = “Left”;
var indexOf:int = menus.indexOf(selected);
trace(“Found selected item “+selected+” at array index: “+indexOf);
Josh,
Much appreciated. I was not aware of the function at the time I posted. Thanks!
Btw you have a nice intro of yourself, really liked it!