Dave Sag
Dave Sag

Reputation: 13486

In CoffeeScript how do you append a value to an Array?

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.

Upvotes: 101

Views: 71079

Answers (3)

Paul Schooling
Paul Schooling

Reputation: 31

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])

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.

Upvotes: 3

suranyami
suranyami

Reputation: 908

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)

Upvotes: 50

Thilo
Thilo

Reputation: 262534

Good old push still works.

x = []
x.push 'a'

Upvotes: 199

Related Questions