javascript - 类似 Liquid 的 Javascript/jQuery 函数:循环
问题描述
JavaScript/jQuery 中是否有类似于下面描述 的 Liquid循环的功能?
循环遍历一组字符串并按照它们作为参数传递的顺序输出它们。每次调用循环时,都会输出作为参数传递的下一个字符串。
输入:
{% 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 - 使用 useState 向 .map 函数中的元素添加一个类
- ms-access - 在 Microsoft Access 2010 的表单中引用列的最后一个值作为默认值
- c++ - 以循环为参数的函数
- python - Python从列表中删除N个连续重复项
- docker-compose - 防止容器启动
- clang - 为什么 Clang 不生成 libstdc++ 中某些库函数的位码?
- huggingface-transformers - 如何使用带有未标记文本的 run_mlm
- javascript - 根据多个搜索词过滤一组对象
- r - 通过 binom.test 或 prop.test 获得相同答案的方法
- javascript - 如何在Javascript中使用RegEx替换破折号后定位一个字母?