【问题标题】:Coffee script multidimensional array creation咖啡脚本多维数组创建
【发布时间】:2014-06-29 03:06:08
【问题描述】:

所以我试图让一个多维数组在 CoffeeScript 中工作。我尝试过使用标准的 Python 列表理解表示法,它使内括号成为字符串或其他东西。所以我不能做 list[0][1] 得到 1,而是得到 list[0][0] = '1,1' 和 list[0][1] = ''

[[i, 1] for i in [1]]

使用类作为存储容器,然后抓取 x 和 y。这给出了“未定义的未定义”,而不是后半部分的“1 1”。

class Position
    constructor:(@x,@y) ->

x = [new Position(i,1) for i in [1]]
for i in x
    alert i.x + ' ' + i.y#'undefined undefined'

i = new Position(1,1)
alert i.x + ' ' + i.y#'1 1'

非常需要能够使用点列表,但我找不到列出它们的方法。我更喜欢使用简单的多维数组,但我不知道如何。

【问题讨论】:

    标签: arrays multidimensional-array coffeescript


    【解决方案1】:

    您只需要使用括号(),而不是方括号[]

    来自 REPL:

    coffee> ([i, 1] for i in [1])
    [ [ 1, 1 ] ]
    coffee> [[i, 1] for i in [1]]
    [ [ [ 1, 1 ] ] ]
    

    您可以看到使用方括号,就像在 Python 中一样,将生成表达式放在一个额外的列表中。

    这是因为括号 () 实际上只存在于 CoffeeScript 中,用于将表达式分配给变量时,所以:

    coffee> a = ([i, 1] for i in [1])
    [ [ 1, 1 ] ]
    coffee> a[0][1]
    1
    coffee> b = [i, 1] for i in [1]
    [ [ 1, 1 ] ]
    coffee> b[0][1]
    undefined
    

    另外,请参阅CoffeeScript Cookbook

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 1970-01-01
      • 2012-04-27
      • 2011-09-03
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2011-11-08
      相关资源
      最近更新 更多