문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top