Coffee script multidimensional array creation

爱⌒轻易说出口 提交于 2019-12-25 02:21:50

问题


So I'm trying to get a multidimensional array to work in CoffeeScript. I have tried with standard Python list comprehension notation, that makes the inner bracket a string or something. so I can't do list[0][1] to get 1, I instead get list[0][0] = '1,1' and list[0][1] = ''

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

Using a class as the storage container, to then grab x and y. Which gives 'undefined undefined', rather then '1 1' for the latter part.

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'

Being able to use a list of points is extremely needed and I cannot find a way to make a list of them. I would prefer to use a simple multidimensional array, but I don't know how.


回答1:


You just need to use parenthesis, (), instead of square brackets, [].

From a REPL:

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

you can see that using the square brackets, as you would in Python, puts the generating expression inside of an extra list.

This is because the parenthesis, () are actually only there in CoffeeScript for when you want to assign the expression to a variable, so:

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

Also, see the CoffeeScript Cookbook.



来源:https://stackoverflow.com/questions/23597404/coffee-script-multidimensional-array-creation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!