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.
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
Array-like objects are objects that have indexed elements. and a length property, similar to arrays, but they may not have all the methods of arrays like push(), pop() & others.
Array destructuring is introduced in ECMAScript (ES6).
// Example array-like object
const arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
[Symbol.iterator]: function () {
let index = 0;
return {
next: () => ({
value: this[index++],
done: index > this.length
})
};
}
};
// Now it's iterable
const array1 = Array.from(arrayLike);
console.log(array1); // output: ['a', 'b', 'c']
const array2 = [...arrayLike];
console.log(array2); // output: ['a', 'b', 'c']
const array3 = Array.prototype.slice.call(arrayLike);
console.log(array3); // output: ['a', 'b', 'c']
Array.prototype.slice.call(arguments)(Polyfillis available though...)[...arguments].Array.prototype.slice.callis very different fromArray.from. It's the fastest and most compatible way to create an array from an existing array-like. It works on all browsers including all IE except IE8- when used on host objects such as a NodeList. However ES6'sArray.fromis much slower because it starts with an array of length 0 which requires log n memory allocations, unlikeArray.prototype.slice.call. And it differs because it fills all the gaps withundefinedand also creates arrays from iterables. So if you're working with an array-like, use[].slice.call