Sunday 24 November 2019

javascript - why `splice.apply(arguments, 0)` fails while `splice.call(arguments, 0)` returns Array




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?


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...