var myArray = ['one', 'two', 'three', 'four']; var curIndex = 0; setInterval(function(){ console.log(myArray[curIndex]); curIndex = (curIndex < myArray.length - 1) ? curIndex + 1 : 0; }, 500);
A collection of handy code snippets in the languages that I use on a daily basis.
May 8, 2014
Return to the beginning of an array with a ternary operator
Often times when iterating and looping over the contents of an array, I want to set the current index to zero if it's reached the last element. Generally this happens in the form of an if/else statement, but I enjoy using a more terse form with the help of a ternary operator. See the code below, and enjoy!
Labels:
array,
java,
javascript,
js,
ternary
Subscribe to:
Posts (Atom)