The array.from () method converts an array-like object or traversable object into a real Array.

So what is an array-like object? The basic requirement for an array-like object is an object with a length attribute.

1. Convert an array-like object to a real array:

let arrayLike = {
    0: 'tom', 
    1: '65',
    2: 'male'And 3:'jane'.'john'.'Mary'].'length'4} :let arr = Array.from(arrayLike)
console.log(arr) // ['tom'.'65'.'male'['jane'.'john'.'Mary']]
Copy the code

So what if the length attribute was removed from the code above? As it turns out, the answer will be an empty array of length 0.

The object has a length attribute, but instead of a numeric attribute, the object has a string name, as follows:

let arrayLike = {
    'name': 'tom'.'age': '65'.'sex': 'male'.'friends': ['jane'.'john'.'Mary'],
    length: 4
}
let arr = Array.from(arrayLike)
console.log(arr)  // [ undefined, undefined, undefined, undefined ]
Copy the code

The result is an array of length 4 with undefined elements

Thus, to convert an array-like object into a true array, the following conditions must be met:

1. This class of array objects must have a length attribute, which specifies the length of the array. If there is no length attribute, the transformed array is an empty array.

2. The property name of this array object must be a numeric or string number

The property names of this array object may or may not be quoted

2. Convert Set data into a real array:

letArr =,45,97,9797,564,134,45642 [12]let set = new Set(arr)
console.log(Array.from(set) // [12, 45, 97, 9797, 564, 134, 45642]Copy the code

Array.from can also take a second argument, similar to the map method of arrays, that is used to process each element and place the value in the returned Array. As follows:

letArr =,45,97,9797,564,134,45642 [12]let set = new Set(arr)
console.log(Array.from(set, item => item + 1)) // [ 13, 46, 98, 9798, 565, 135, 45643 ]
Copy the code

Quickly create an array of 1 to 20

Array.from({length:20},(t,i)=>i+1)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Copy the code

The simulation generates 10,000 pieces of data

Const originNews = array. from({length: 10000}, (v, k) => ({content: 'news${k}`}))Copy the code

3, convert string to array:

let  str = 'hello world! ';
console.log(Array.from(str)) // ["h"."e"."l"."l"."o".""."w"."o"."r"."l"."d"."!"]
Copy the code

The array. from argument is a real Array:

The console. The log (Array. The from (,45,47,56,213,4654,154 [12]))Copy the code

In this case, array. from returns a new Array that looks exactly like it

Groups arrays by specified size and can be used for paging, data slicing, and asynchronous manipulation of data.

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
Copy the code