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 , as it has been said by others before me, Array.prototype.splice.apply(arguments, 0) is (roughly) equivalent to arguments.splice([0])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