Posted By

discorax on 01/09/08


Tagged

actionscript search array 20


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

crashdr
eorwoll
emilymer


array_search function "needle in a haystack"


 / Published in: ActionScript
 

I use this function in php a lot, and now I can use it in my Flash AS2 projects. Searches through an array for a string value and returns the index of that string. Can be modified to search for other data types ie. MovieClip, Number, etc...

  1. // function to search through an array to see if a value is in there.
  2. // Returns the index of the item in the array if found otherwise returns -1
  3. // needle can be other data types, including MovieClip, Number, etc...
  4.  
  5. function array_search(needle:String, haystack:Array):Number {
  6. var i:Number;
  7. var found:Boolean = false;
  8. for (i=0; i<haystack.length; i++) {
  9. if (haystack[i] == needle) {
  10. found = true;
  11. break;
  12. }
  13. }
  14. if (found == true) {
  15. return (i);
  16. } else {
  17. return (-1);
  18. }
  19. }
  20.  
  21. function searchArray():Void{
  22. var arrayIndex:Number = array_search(mc, inputArray);
  23. if (arrayIndex != -1) {
  24. // do something
  25. } else {
  26. //trace("Not In Array");
  27. }
  28. }

Report this snippet  

You need to login to post a comment.