Javascript "Arguments" Keyword

I understand what I can call Array.prototype.slice.call(arguments, 1)to return the tail of an array.

Why does this code not return [2,3,4,5]?

function foo() {  
    return Array.prototype.slice.call(arguments,1);
}

alert(foo([1,2,3,4,5]));
+5
source share
3 answers

Because you only pass one argument - an 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.

, , arguments "" . - arguments - , arguments - , , .

+9

arguments - , , (, arguments.callee).

arguments :

arguments {
    0: [1,2,3,4,5],
    length: 1,
    other properties here
}

, , . arguments[0] arry.

+10

Because there argumentsis {0: [1,2,3,4,5], length: 1}, which is an object that looks like an array, with one element. The tail of an array with one element is an empty array.

Or change the function definition:

function foo(arr) {  
    return Array.prototype.slice.call(arr,1);
}

or call the function with:

foo(1,2,3,4,5);
+3
source

All Articles