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'

6 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

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

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

sara laurence said...

Whether its about designing and development the most important thing is your professional laptop from msi i7 laptop as a professional laptop will make your work fluently.

Aaron Yan said...

i am very satisfied with your post. Thanks for sharing!. You can also visit my post.
graphpadprism
amplitube4complete
360totalsecurity
cranesongpeacock

Post a Comment

Cron Design Studio: Dublin based web design & software development