Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 900
Mathias Nielsen Avatar asked Dec 17 '25 10:12

Mathias Nielsen


1 Answers

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
like image 105
Joe Avatar answered Dec 19 '25 23:12

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!