JS返回数组中的next,无限循环

发布于 2024-12-09 09:43:45 字数 248 浏览 3 评论 0原文

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

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

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

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

我无法弄清楚,而且谷歌搜索也很难。 有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温柔戏命师 2024-12-16 09:43:46

这是一个有趣的小函数:

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

}

像这样调用:

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

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
漫漫岁月 2024-12-16 09:43:46
// 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();
// 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();
墨小沫ゞ 2024-12-16 09:43:46

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文