21 September 2012

Loop Javascript (or Actionscript!) array based on index

Looping arrays is particularly useful for things like photo galleries and other iterative processes where you want the "next photo" button on a gallery to continue from the beginning of the album after the user passes the last photo.

In my humble opinion, I believe this functionality should be built into the core of Ecmascript ( For example, something like myArray[-2] should really return the second last element in the array) but alas we have to write it ourselves, so here goes...




//loop array indexes & return the specified element:
function getElement(index,fromArray){
    while( index>fromArray.length-1 ){ index -= (fromArray.length);}
    while( index<0 ){ index = (fromArray.length)+index }
    return(fromArray[index])
}

//EXAMPLE:
var a = ['a1','b2','c3','d4','e5'] //create a simple 5 element array

alert(getElement(6,a)) //alerts 'b2'
alert(getElement(-2,a)) //alerts 'd4'

5 comments:

Post a Comment

Cron Design Studio: Dublin based web design & software development