Array. The prototype. Slice. The call () to an Array (the arguments, NodeList), the class String (String) into an Array.

Array.from() converts class arrays (arguments,NodeList), iterable objects (Set,Map), and strings (String) into arrays.

Array. The prototype. Slice. Call the commonly used sample ()

Array. The prototype. Slice. Call (arrayLike, start, end) converts arrayLike class Array to Array, and from the start to the subscript subscript for end intercepting Array.

function makeArray (arrayLike) {
    return Array.prototype.slice.call(arrayLike);
}
function doSomething() {
    var args = makeArray(arguments);
    / / use the args. }Copy the code

In the example above, the slice() method is executed with this as an array-like object (arguments), and the slice() object just needs a numeric index and length attribute to work fine. Arguments can be converted to an array. For example, the following objects can be converted to arrays:

var obj = {0:'hello'.1:'world'.length:2};
console.log(Array.prototype.slice.call(obj)); // ["hello", "world"]
Copy the code

Objects without the length attribute cannot

var obj = {0:'hello'.1:'world'}; // No length attribute
console.log(Array.prototype.slice.call(obj)); / / []
Copy the code

Common examples of array.from ()

Array.from(arrayLike, mapFn, thisArg) –> Array.from(arrayLike).map(fn(), thisArg)

Example 1 — Turn an array of classes into an array

function doSomething () {
    var args = Array.from(arguments);
    / / use the args. }Copy the code

This method is a new method for ECMAScript6, which makes it cleaner to convert an array-like object into an array.

The array.from () method call creates a new Array based on the elements in the Arguments object. Args is an instance of Array that contains the same values at the same location in the arguments object.

Example 2 — Convert a Set collection to an array

let arr = [1.2.3.4.5.6.7.8.9]
let set = new Set(arr)
console.log(Array.from(set) / /,2,3,4,5,6,7,8,9 [1]
Copy the code

Example 3 — Convert a Map collection to an array

const myMap = new Map().set(true.7)
console.log(myMap); // Map(1) {true => 7}
console.log(Array.from(myMap)) // [[true,7]]
// If you want to change it to a one-dimensional array
console.log(Array.from(myMap).flat()) // [true ,7]
Copy the code