Coffee script creating multidimensional array
So I'm trying to get a multidimensional array to work in CoffeeScript. I've tried using standard Python notation, which makes the inner parenthesis 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 a storage container to then grab x and y. Which gives 'undefined undefined' and not '1 1' for the last 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'
The ability to use a list of items is badly needed, and I can't find a way to make a list of them. I would rather use a simple multidimensional array, but I don't know how.
source to share
You just need to use parentheses ()
instead of square brackets []
.
From the REPL:
coffee> ([i, 1] for i in [1])
[ [ 1, 1 ] ]
coffee> [[i, 1] for i in [1]]
[ [ [ 1, 1 ] ] ]
you can see that using square brackets, as in Python, puts the generation expression in an additional list.
This is because parentheses ()
actually only exist in CoffeeScript if you want to assign an 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 Coffeebook Cookbook .
source to share