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'

3 comments:

Anonymous said...

re: fading banner

Why does the script start banner #5 first even if you told it to start with banner #1 first using the "body onload" code you provided???

I noticed that even your demo does this as well!!!????!!!

All my script settings are at 100% default!!!

I hope this can be fixed so I can use this awesome script.

Thank you

Meiqing Xu said...

jordan shoes
canada goose jackets uk
hermes handbags
kobe shoes
michael kors uk
ralph lauren
buy red bottoms
louis vuitton handbags outlet
rolex replica watches
christian louboutin outlet
20161228caiyan

林平平 said...

nike outlet store
mulberry outlet
ugg boots
north face jackets
nmd adidas
adidas nmd
ralph lauren uk
coach factory outlet
uggs clearance
louis vuitton outlet store

Post a Comment

Cron Design Studio: Dublin based web design & software development