ECMAScript 6 supports a generic Array method for converting an array-like object into one of its own.It is Array.from(). This method is very useful while converting iterable objects to arrays, code will be much cleaner and no need to use split or slice hacks. It has the following syntax:
Array.from (arrayLike [ , mapfn [ , thisArg ] ] );
Parameters –
arrayLike – Required. An array-like object or an iterable object.
mapfn – Optional. A mapping function to call on each element in arrayLike.
thisArg – Optional. Specifies the this object in the mapping function.
The following example returns an array from a collection of DOM element nodes.
var elemArr = Array.from(document.querySelectorAll('*')); var elem = elemArr[0]; // elem contains a reference to the first DOM element
The following example returns an array of characters.
var charArr = Array.from("abc"); // charArr[0] == "a";
The following example returns an array of objects contained in the collection.
var setObj = new Set("a", "b", "c"); var objArr = Array.from(setObj); // objArr[1] == "b";
The following example shows the use of arrow syntax and a mapping function to change the value of elements.
var arr = Array.from([1, 2, 3], x => x * 10); // arr[0] == 10; // arr[1] == 20; // arr[2] == 30;