I know there are two ways to convert Array-like objects to Array.
Array.prototype.slice.call(arguments)
Array.from(arguments)
I wonder what's the differences between them , which one should I use to convert Array-like objects.
I know there are two ways to convert Array-like objects to Array.
Array.prototype.slice.call(arguments)
Array.from(arguments)
I wonder what's the differences between them , which one should I use to convert Array-like objects.
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
Array.prototype.slice.call(arguments)
works faster in many browser than Array.from(arguments)
.
You can look at the results here.
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.
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