JavaScript/jQuery 中是否有类似于 Liquid 的函数 cycle 如下所述?
循环一组字符串并按照它们作为参数传递的顺序输出它们。每次调用循环时,都会输出作为参数传递的下一个字符串。
输入:
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
输出:
one
two
three
one
最佳答案
你可以使用闭包,
在外部范围内,您定义一个跟踪索引的变量;
当返回的函数递增或重置索引时,
并返回相应的项目。
这是一个例子:
function cycle(arr) {
cycle.i = -1
//return a closure for cycling
return function() {
cycle.i = cycle.i < arr.length - 1 ? cycle.i + 1 : 0
return arr[cycle.i]
}
}
var it = cycle(['one', 'two', 'three'])
setInterval(function() {
console.log(it())
}, 500)
关于Javascript/jQuery 函数类似于 Liquid : cycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668014/