3

I have a list of strings like so;

var mystrings = [
    'apple',
    'banana',
    'orange'
]

I would like a function I can call at anytime to get the next string. And when the end of the list is reached, start over and get the first one again.

I am using it for a list of CSS classes that must be applied in the order from the list, but I will not be looping over that list when they are needed.

I can't figure it out and it is somehow hard to google. Any ideas?

Mathias Nielsen
  • 1,560
  • 1
  • 17
  • 31

3 Answers3

6

Here's a fun little function:

function enumerator(array) {
    var index = 0;
    return function () {
        return array[index++%array.length]
    }

}

called like this:

var next = enumerator(["a", "b"]);
next(); // a
next(); // b
next(); // a
Joe
  • 80,724
  • 18
  • 127
  • 145
1
// Your array is declared in global scope
var mystrings = [
    'apple',
    'banana',
    'orange'
];

// A global index variable...
var strIndex = 0;
function getNextString() {
   // If you reached the end of the array, reset to 0
   if (strIndex === mystrings.length - 1) {
       strIndex = 0;
       return mystrings[strIndex];
   }
   // Otherwise, increment it and return the new value
   else return mystrings[++strIndex];
}

// Call it as
var currentString = getNextString();
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
-1

Use an external index variable and increment or reset it to 0 on each call

Adam Bergmark
  • 7,316
  • 3
  • 20
  • 23