12

I know there are two ways to convert Array-like objects to Array.

  1. Array.prototype.slice.call(arguments)
  2. Array.from(arguments)

I wonder what's the differences between them , which one should I use to convert Array-like objects.

Jian
  • 3,118
  • 2
  • 22
  • 36
  • 1
    As far as [__Browser compatibility__](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility) is concerned, go with the `Array.prototype.slice.call(arguments)`([`Polyfill`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Polyfill) is available though...) – Rayon May 03 '16 at 04:33
  • 2
    Or `[...arguments]`. –  May 03 '16 at 04:40
  • But be careful in old IE 8 and lower. If host objects are passed as *this* to built–in methods (e.g. passing an HTML collection as *this* to *slice*) you will get an error. However, if you have a polyfill for [*from*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Polyfill), that will not be an issue. – RobG May 03 '16 at 04:57

4 Answers4

13

Array.prototype.slice.call has been the long-standing mechanism for converting array-like objects to arrays. If you are looking for browser compatibility use this (although it appears that on some older browsers like IE8 and below this will not work at all).

Array.from was introduced ECMA6 in June of 2015. It accomplishes the same thing as the prior mechanism, only in a more fluent and concise manner. In addition Array.from can convert more structures into arrays such as generators.

Learn about array.from

world
  • 3,932
  • 2
  • 10
  • 12
  • 1
    Actually `Array.from` accomplishes **more**, since it can turn generators into arrays etc. –  May 03 '16 at 04:42
  • 1
    For the record, [*ECMA-262*](http://www.ecma-international.org/publications/standards/Ecma-262.htm) is the name of the standard (all versions). *ECMAScript* is the name of the language. [*Edition 6*](http://www.ecma-international.org/ecma-262/6.0/index.html) is the current version of ECMA-262, its short name is *ECMAScript 2015*. – RobG May 03 '16 at 05:03
3

Array.prototype.slice.call(arguments) works faster in many browser than Array.from(arguments).

You can look at the results here.

0

If you want your code to be portable, use the first method. The second method is part of ECMAscript 6 and is therefore not well supported across a range of browsers.

theharls
  • 163
  • 7
0

slice works on anything that has a length property, which arguments conveniently does.

Array.from simply convert Array-like or Iterable objects into Array instances.

Unfortunately, Array.from and Rest Parameters are currently only implemented in newer versions of Firefox and Google Chrome

Please refer to link

Community
  • 1
  • 1