Reputation: 15830
Here's a simple function I invented to test out JavaScript's argument
object versus rest parameters.
function f(a, b, ...theArgs) {
console.log(theArgs);
console.log(arguments);
return arguments;
}
if I call this function, say with these parameters: f(1,2,6,5,8,9,10,'a')
I'll get two console logs and then the argument objects is returned. All great.
However, if I pass this function to:
Array.prototype.slice(f(1,2,6,5,8,9,10,'a'), f.length)
, I will get an empty array back instead of an array like [6,5,8,9,10,'a']
-- it appears that in this case my function is returning an empty array instead of the arguments object.
Why is that? Here's a snapshot of my console:
Upvotes: 0
Views: 333
Reputation: 33496
Array.prototype
is the empty array that your code is slicing on, not the result of f
.
The first parameter to slice
must be a number. In your code, f
returns an object. If you want to change the this
value of the slice
function so that it slices your object instead, use .call
:
Array.prototype.slice.call(f(1, 2, 6, 5, 8, 9, 10, 'a'), f.length)
function f(a, b, ...theArgs) {
//console.log(theArgs);
//console.log(arguments);
return arguments;
}
console.log(Array.prototype.slice.call(f(1, 2, 6, 5, 8, 9, 10, 'a'), f.length));
Upvotes: 1