Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array-like objects, Array.prototype.slice or Array.from

Tags:

javascript

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.

like image 337
theJian Avatar asked May 03 '16 04:05

theJian


2 Answers

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

like image 104
world Avatar answered Sep 20 '22 04:09

world


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

You can look at the results here.

like image 28
Andrey Vershinin Avatar answered Sep 22 '22 04:09

Andrey Vershinin