Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why `splice.apply(arguments, 0)` fails while `splice.call(arguments, 0)` returns Array [duplicate]

Tags:

javascript

I'm trying to turn arguments variable which is accessible inside function into an array. I've tried two ways:

Array.prototype.splice.apply(arguments, 0) //fails
Array.prototype.splice.call(arguments, 0) //return array

Can you please guys elaborate on why the first option fails while the second one succeeds?

like image 707
Max Koretskyi Avatar asked Jul 29 '14 13:07

Max Koretskyi


1 Answers

That's because Array.prototype.splice.apply(arguments, 0) is (roughly) equivalent to arguments.splice([0]), as it has been said by others before me, apply expects an Array as its second argument. If you wanted to retrieve the n-first parameters, you could do Array.prototype.splice.apply(arguments, [0,n]) which would be (roughly) equivalent to arguments.splice.(0,n).

On the contrary, call works with any type of parameters. Array.prototype.splice.call(arguments, 0) is (roughly) equivalent to arguments.splice(0), and since splice expects an integer as its first argument and not an array, the second solution works (but not the first one). Thus, Array.prototype.splice.apply(arguments, [0]) would also work as Jeroen Noten suggested it.

Please note that the "equivalences" I'm referring to would not actually work since arguments is not an Array but rather an Array-like object.

However, the technique you mentioned is frequently used to turn an Array-like object into a proper Array.

EDIT : I edited my answer as it contained a big mistake. Thanks to cookiemonster for the correction.

like image 105
Waldo Jeffers Avatar answered Oct 15 '22 12:10

Waldo Jeffers