Saturday, January 27, 2007

array functions tutorial -part I-


Recently I needed some arrays search functions for better performance so I wrote few of them. First one is simple.


function search(wor, arr){
   var exist = false;
   for(i=0; i< arr.length; i=i+1){
     if(arr[i ]==wor){
       trace("Element exist on position "+i);
       exist = true;
     }
   }
   if(!(exist)){
     trace("Element don't exist in array.");
   }
}

In for loop we ask if wor is identical to any of array's elements. Note that we use == not = (common mistake). Boolean variable exists is responsible for finding our word in array. If word multiple times in array, all positions will be find. Second function is almost the same. Difference is that this one returns true or false. True if wor is in arr, false otherwise. It goes like this.

function searchB(wor, arr){
   var exist = false;
   for(i=0; i< arr.length; i=i+1){
     if(arr[i]==wor){
       return true;
       exist = true;
     }
   }
   if(!(exist)){
     return false;
   }
}

This function will end on first appearence of wor in arr. If wor don't exist in arr, function will return false. You can test these functions like this:

_root.onMouseDown=function(){
   planets = new Array("Merkur", "Venus", "Earth", "Mars");
   habitable = "Earth";
   what = search(habitable, planets);
   trace(what);
}

Similar for searchB function.

-end of part I-
Posted by flanture at 14:45:36 | Permanent Link | Comments (1) |
Comments
1 - Thanks for the array search thing, saved a major headache and works better than Colin Moock one did for me. (Comment this)

Written by: Andrew at 2007/02/20 - 14:08:26
Write a comment