Skip to content Skip to sidebar Skip to footer

Why Does Array Slice Convert Javascript Arguments To Array

Why does applying the slice method to the javascript arguments value as follows Array.prototype.slice.call(arguments) convert it to an array? If slice is used on arrays, and argume

Solution 1:

From the EcmaScript specification on Array.prototype.slice:

NOTE The slice function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the slice function can be applied successfully to a host object is implementation-dependent.

And so, slice works on every object that has a length property (like Arguments objects). And even for those that do not, it then just returns an empty array.


Solution 2:

Right, this is a trick that takes advantage of the fact that arguments are an enumerable list. It works on other enumerable lists too (for example nodelists).


Post a Comment for "Why Does Array Slice Convert Javascript Arguments To Array"