actionscript 3 - Finding the next element in an unordered array -
i have unordered array of can not sort. not because can't, because order critical application. not knowing index of element have, how find element following it?
what have devised far:
/** * @return int - id || -1 out of bounds */ public function getnextid(currentid:int):int{ var found:boolean = false; each(var id:int in mids){ if(found){ return id; } if(id == currentid){ found = true; } }return -1; }
i merely asking because seeking better solution possibly doesn't call loop , interested in educating myself better on options available in as3.
thanks!
try this:
public function getnextid(currentid:int):int { var index:int = mids.indexof(currentid); if (index == -1 || index + 1 >= mids.length) return -1; return mids[index + 1]; }
the indexof
function gets first index in array corresponds search parameter. if doesn't exist, returns -1. can use in conjunction array index accessor syntax (using brackets []
) find right value.
Comments
Post a Comment