My understanding is that I can call Array.prototype.slice.call(arguments, 1)
to return the tail of an array.
Why won't this code return [2,3,4,5]
?
function foo() {
return Array.prototype.slice.call(arguments,1);
}
alert(foo([1,2,3,4,5]));
arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that function.
typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.
JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.
Because you're only passing one argument — the array.
Try alert(foo(1,2,3,4,5));
Arguments are numbered from 0 in JavaScript, so when you start your slice at 1 and pass 1 argument, you get nothing.
Note that it can hamper optimization to allow the arguments
object to "leak" out of a function. Because of the aliasing between arguments
and the formal parameters, an optimizer can't really do any static analysis of the function if the arguments
object gets sent somewhere else, because it has no idea what might happen to the parameter variables.
arguments
is an array-like object that lists the arguments and a few other properties (such as a reference to the current function in arguments.callee
).
In this case, your arguments
object looks like this:
arguments {
0: [1,2,3,4,5],
length: 1,
other properties here
}
I think this explains the behaviour you're seeing quite well. Try removing the array brackets in the function call, or use arguments[0]
to access the arry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With