Problem
You want to convert the array-like object arguments
to a real array.
Ingredients
- the
Array
prototype - the
slice()
method - the
call()
method
Directions
-
Given: a function that takes different parameters and accesses them via the
arguments
object.function printAllArguments() { let values = arguments; for(let i=0; i<values.length; i++) { console.log(values[i]); } } printAllArguments(2, 3, 4);
-
Get a reference to the
Array
prototype.function printAllArguments() { let arrayPrototype = Array.prototype; ... } ...
-
Get a reference to the
slice()
method. (Theslice()
method creates a shallow copy of a part of an array and returns a new array. If you omit any parameters it copies the whole array.)function printAllArguments() { let arrayPrototype = Array.prototype; let sliceMethod = arrayPrototype.slice; ... } ...
-
Call the
slice()
method using thecall()
method.function printAllArguments() { let arrayPrototype = Array.prototype; let sliceMethod = arrayPrototype.slice; let values = sliceMethod.call(arguments); for(let i=0; i<values.length; i++) { console.log(values[i]); } } printAllArguments(2, 3, 4);
-
Combine the code from the previous three steps.
function printAllArguments() { let values = Array.prototype.slice.call(arguments); for(let i=0; i<values.length; i++) { console.log(values[i]); } } printAllArguments(2, 3, 4);
-
Voilá, there you got a real array now, e.g., you can call array methods like
forEach
,map
,reduce
andfilter
on it.function printAllArguments() { let values = Array.prototype.slice.call(arguments); values.forEach(function(value) { console.log(value); }); } printAllArguments(2, 3, 4);
Notes
- This recipe is also known as method borrowing.
Alternative recipes
-
Since ES2015: use
Array.from()
to create an array based on an array-like object:function printAllArguments() { let values = Array.from(arguments); values.forEach(function(value) { console.log(value); }); } printAllArguments(2, 3, 4);
-
And while you are in ES2015 you can also use fat arrow functions:
function printAllArguments() { let values = Array.from(arguments); values.forEach((value) => { console.log(value); }); } printAllArguments(2, 3, 4);
-
And while you are at it, use rest parameters, which are real arrays:
function printAllArguments(...values) { values.forEach((value) => { console.log(value); }); } printAllArguments(2, 3, 4);