Array.inArray() method in ActionScript2
Posted on 24th October 2007 in ActionScript |
For those of you who are still developing in Flash ActionScript2, an Array method similar to the PHP’s in_array() might come in handy.
The following code creates the prototype and finds a match recursively type-wise:
Array.prototype.inArray = function(element) { for (i in this) { if (this[i] === element) { return true; } else if (this[i] instanceof Array) { return this[i].inArray(element); } } return false; }; ASSetPropFlags(Array.prototype, "inArray", 1);
Sample:
var myArr:Array = new Array("flashbit", "tekkie", "flash", "article", 6, 80, new Array(100, 4, 5, new Array(8, "another article"))); var isInThere:Boolean = myArr.inArray('tekkie'); trace(isInThere ? "it's there!" : "it's not there!");
The above sample would trace it’s there!.
myArr.inArray('6') would return false and trace it’s not there! while myArr.inArray(6) would return true.
Click here for the attached ActionScript.

2 Responses
Is there a way to implement this function into a class that i’ve created? I’d like to be able to check if an element is in an array while using one of my classes defined functions.
If you need to convert this functionality to ActionScript 3, this article on Adobe LiveDocs might help you out.