【问题标题】:iterating previous next in a loop在循环中迭代上一个下一个
【发布时间】:2015-08-27 11:04:57
【问题描述】:

是否有一种很好的惯用方式来迭代 Coffeescript 中的数组但同时访问循环内的当前项和下一项?例如在 Python 中你可以这样做:

[f(current, next) for current, next in zip(a, a[1:])]

【问题讨论】:

    标签: javascript coffeescript


    【解决方案1】:

    我选择了这个:

    (f(a[i], a[i-1]) for i in [1..segment.length-1])
    

    我想不出更好的办法。

    【讨论】:

      【解决方案2】:

      这样的事情怎么样?

      array = ['a', 'b', 'c', 'd']
      
      for value, index in array
       current = value
       next = if array[index+1] then array[index+1] else null
       alert "#{current} at #{index} #{next}"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-23
        • 2019-08-21
        • 2019-07-26
        • 2020-09-07
        • 2015-07-09
        • 1970-01-01
        • 2016-04-07
        • 2021-04-09
        相关资源
        最近更新 更多