Search code examples
javascriptloopscycle

JS return next in array, cycle endlessly


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?


Solution

  • 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