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开发者_JAVA技巧 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?
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
// 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();
Use an external index variable and increment or reset it to 0 on each call
精彩评论