Neues Node.js-Buch
Alle Artikel

Convert arguments object to array

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

  1. 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);
  1. Get a reference to the Array prototype.

    function printAllArguments() {
      let arrayPrototype = Array.prototype;
      ...
    }
    ...
  2. Get a reference to the slice() method. (The slice() 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;
      ...
    }
    ...
  3. Call the slice() method using the call() 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);
  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);
  5. Voilá, there you got a real array now, e.g., you can call array methods like forEach, map, reduce and filter 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);