How to Convert Arguments Object to an Array
The arguments object is an Array-like object which represents the arguments passed in when executing a function. To convert it to Array, there are several methods that we are going to discuss in the scope of this article.
There is method in ECMAScript 2015 that converts an arguments into an array. You can use the Array.from() or the spread operator like this:
The Array.from() method is used to create a new, shallow-copied Array instance from an array-like or iterable object.
If you use ES6 the rest parameters can help you with the task:
The rest parameter syntax allows representing an indefinite number of arguments as an Array.
When the slice() method is called normally, it means that this is an Array, and the method iterates over that Array and works properly.
The this in the slice() function is accepted as an Array as when you call the following the object automatically becomes the value of this in the method():
Let’s consider the following case:
The [1,2,3] Array set will be as the value of this in slice().
But if you substitute something else, for example, that has a numeric .length property or a set of properties that are numeric indices as the this value, it should work. This kind of object is often called an array-like object.
The call() and apply() methods allow setting the value of this in a function manually. If you set the value of this in slice() to an array-like object, it will consider it as an Array, and perform the same action as in the case of arrays.
Let’s take a look at this example:
This is not an Array, but if you can set it as the this value of slice(), then it will work as it looks like an Array.
Here is how the slice() method works when you set an arguments object as the this value.