I have a function that should return all but the first argument
foo = -> arguments[1..]
foo(0,1,2,3,4)
unfortunately arguments is not an array but an object.
What is the best way to convert the object into an array?
There are a few CoffeeScript-ish options using a splat to take care of array-ifying arguments. You can use slice:
f = (args...) -> args.slice(1)
Or you could use a range instead of directly calling slice:
f = (args...) -> args[1..-1]
You can simplify the second version because:
Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.
So you could leave off the -1 and say just:
f = (args...) -> args[1..]
instead. Thanks to scar3tt for pointing this out.
(args...) that directly using arguments doesn't always give you.args... is essentially turned into [].slice.call(arguments) by the coffeescript compilerYou can ignore the first argument and use splats to capture the rest:
foo = (_, rest...) -> rest
You could also do something like foo = (args...) -> args[1...], but that'll compile to two different calls to Array#slice (unlike the first snippet).
[1...] just to illustrate that I cannot do array operations...arguments as an array in CoffeeScript is to simply declare the function as (args...) -> and then use args which is a real array.What found is to use Array.prototype.slice:
coffee> foo = -> Array.prototype.slice.apply(arguments)[1..]
[Function]
coffee> foo(0,1,2,3,4)
[ 1, 2, 3, 4 ]
Another version would be
[].slice.call(arguments)