Array.from ()
Array.from
The Array-like method is used to convert two types of objects to a true array: An array-like object (A. iterable) and an object that can be traversed (including ES6 new data structure set and map).
1Let Arraylike = {2' 0 ': ' A ',3' 1 ': ' B ',4' 2 ': ' C ',5Length:36 };7 8 //the writing of ES59 varARR1 = [].slice.call (arraylike);//[' A ', ' B ', ' C ']Ten One //the writing of ES6 ALet arr2 = Array.from (arraylike);//[' A ', ' B ', ' C ']
In practice, a common array-like object is the NodeList collection returned by the DOM operation, as well as the objects inside the function arguments
. Array.from
they can be converted to real arrays.
// NodeList Object Let PS = Document.queryselectorall (' P '); Array.from (PS). ForEach (function (p) { console.log (p);}); // arguments Object function foo () { var args = array.from (arguments); // ...}
In the above code, the querySelectorAll
method returns an array-like object that can only be used if the object is converted to a true array forEach
.
As long as the data structure with the iterator interface is deployed, Array.from
it can be converted to an array.
Array.from
You can also accept the second parameter, which acts like an array map
, to process each element and put the processed value into the returned array.
Array.from (arraylike, x = x * x); // equivalent to Array.from (arraylike). map (x = = x * x); Array.from ([1, 2, 3], (x) = x * x)// [1, 4, 9]
Array.of ()
Array.of
method is used to convert a set of values into an array.
// [3,11,8] // [3] // 1
Array.of
Can basically be used to replace Array()
or new Array()
, and there are no overloads caused by different parameters. It behaves very uniformly.
// the Array.of method can be simulated with the following code. function arrayof () { return [].slice.call (arguments); //ES5
}
Extension of the ES6 array