function someFunc() {
var args = Array.prototype.slice.call(arguments);
return args;
}
someFunc(1,2,3); //[1, 2, 3]
The arguments
object is an array-like object (not an array) local to every function and contains an entry for each argument passed into the function.
In the above, we use Array.prototype
to create an instance of an array. It could also be written this way var args = [].slice.call(arguments);
.
Then we use the slice()
method. Slice can be used for array-like objects (in this case our arguments
object) as long as you bind the method to the object. For binding in this case, we use call()
. You could also use other binding functions such as apply()
.
The call()
method takes in the arguments
object, which is the this
value provided for slice()
.
It's worth noting that in EcmaScript 2015 this can be done in a simpler way using Rest parameters and the spread operator. The following is the ES2015 equivalent:
function someFunc(...args) {
return args;
}
someFunc(1,2,3); //[1, 2, 3]