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 }

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'


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

Unknown 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

Unknown 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

obat kencing manis said...

It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing.
obat gabagen
obat ginjal bengkak
obat keloid
obat limpa bengkak
obat thalasemia
obat kencing tidak tuntas
obat tbc tulang

Unknown said...

polo ralph lauren outlet
air max 2018
cheap jordans
canada goose jackets
coach outlet store online
dsquared2 jeans
cheap jordan shoes
oakley sunglasses wholesale
michael kors outlet clearance
coach outlet store online

Juliana Kho said...

login cbet

joker123 live chat

Eliza said...

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. website design

yanmaneee said...

kyrie irving shoes
golden goose
yeezy sneakers
golden goose sneakers
curry 8
off white shoes
curry 6
jordan shoes
kyrie 5 spongebob
pandora jewelry

Post a Comment

Cron Design Studio: Dublin based web design & software development