首页 > 解决方案 > 类似 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

我一直在尝试查看loop, forEachdo/while但无法理解。
感谢您的任何建议。

标签: javascriptjqueryiterationliquidcycle

解决方案


您可以使用闭包,
在外部范围内定义一个跟踪索引的变量;
而返回的函数递增或重置索引,并返回相应的项目。

这是一个例子:

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)


推荐阅读