JS在数组中返回,循环不休

时间:2011-10-12 19:13:39

标签: javascript loops cycle

我有一个像这样的字符串列表;

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

我想要一个我可以随时调用的函数来获取下一个字符串。 当达到列表的末尾时,重新开始并再次获得第一个。

我将它用于必须按照列表顺序应用的CSS类列表,但是在需要时我不会循环遍历该列表。

我无法弄明白,谷歌有点难。 有什么想法吗?

3 个答案:

答案 0 :(得分:6)

这是一个有趣的小功能:

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

}

这样叫:

var next = enumerator(["a", "b"]);
next(); // a
next(); // b
next(); // a

答案 1 :(得分: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();

答案 2 :(得分:-1)

使用外部索引变量并在每次调用时将其递增或重置为0

相关问题