【问题标题】:Javascript / jQuery function similar to Liquid: cycle类似于 Liquid 的 Javascript/jQuery 函数:循环
【发布时间】:2018-06-03 15:28:24
【问题描述】:

JavaScript/jQuery 中是否有类似于 Liquid cycle 的函数,如下所述?

遍历一组字符串并按照它们作为参数传递的顺序输出它们。每次调用循环时,都会输出下一个作为参数传递的字符串。

输入:

{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}
{% cycle 'one', 'two', 'three' %}

输出:

one
two
three
one

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

【问题讨论】:

    标签: javascript jquery iteration liquid cycle


    【解决方案1】:

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

    这是一个例子:

    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)

    【讨论】:

    • 有效!从来没想过关门。非常感谢您的快速回答。
    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2011-09-02
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多