【问题标题】:Loop within loop coffeescript循环内循环咖啡脚本
【发布时间】:2015-07-15 19:41:27
【问题描述】:

在coffeescript中我怎样才能有for循环和for循环

我正在尝试使用以下代码,但它不起作用

scale = filenames.length
for key, filename in filenames
    x = key
    for i in [x...scale]
        alert(i)

filenames 是一个文件名数组

当我尝试跟随时,它会起作用

for key, filename in filenames
    x = key
    for i in [0...scale]
        alert(i)

【问题讨论】:

    标签: javascript ruby-on-rails coffeescript


    【解决方案1】:

    在 Coffeescript 中,传递给 for ... in 的第一个参数将填充实际的 value,第二个可选参数用于 index

    x = key在这段代码中也不是必须的,你可以直接参考key

    结果应该如下:

    filenames = ['One.txt', 'Two.txt', 'Three.txt'] # a dummy array for testing purposes
    scale = filenames.length
    
    # now the actual loop
    for filename, key in filenames
        for i in [key...scale]
            alert i
    

    参见CoffeeScript - Loops and Comprehensions 中的第二个示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 2015-12-12
      • 2012-06-14
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 2019-02-23
      相关资源
      最近更新 更多