What is the prescribed way to append a value to an Array in CoffeeScript? I've checked the PragProg CoffeeScript book but it only discusses creating, slicing and splicing, and iterating, but not appending.
在CoffeeScript中,为数组添加值的指定方法是什么?我已经检查了PragProg CoffeeScript书,但是它只讨论创建、切片和拼接,以及迭代,而没有附加。
3 个解决方案
#1
181
Good old push
still works.
好的旧推仍然有效。
x = []
x.push 'a'
#2
48
Far better is to use list comprehensions.
最好是使用列表理解。
For instance rather than this:
例如:
things = []
for x in list
things.push x.color
do this instead:
这样做:
things = (x.color for x in list)
#3
2
If you are chaining calls then you want the append to return the array rather than it's length. In this case you can use .concat([newElement])
如果您正在链接调用,那么您希望append返回数组,而不是返回它的长度。在本例中,可以使用.concat([newElement]))
Has to be [newElement] as concat is expecting an array like the one its concatenating to. Not efficient but looks cool in the right setting.
必须是[newElement],因为concat希望得到一个与其连接的数组。效率不高,但在合适的环境下看起来很酷。
#1
181
Good old push
still works.
好的旧推仍然有效。
x = []
x.push 'a'
#2
48
Far better is to use list comprehensions.
最好是使用列表理解。
For instance rather than this:
例如:
things = []
for x in list
things.push x.color
do this instead:
这样做:
things = (x.color for x in list)
#3
2
If you are chaining calls then you want the append to return the array rather than it's length. In this case you can use .concat([newElement])
如果您正在链接调用,那么您希望append返回数组,而不是返回它的长度。在本例中,可以使用.concat([newElement]))
Has to be [newElement] as concat is expecting an array like the one its concatenating to. Not efficient but looks cool in the right setting.
必须是[newElement],因为concat希望得到一个与其连接的数组。效率不高,但在合适的环境下看起来很酷。