In es6, you can use the from() method of the Array object to convert the object into an array. This method can convert an array-like object or a traversable object into a real array; the syntax is "Array.from(object)".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
In es6, you can use the from() method of the Array object to convert the object into an array.
The Array.from() method converts an array-like object or traversable object into a real array.
So what is an array-like object? The most basic requirement for the so-called array-like object is an object with the length attribute.
1. Convert array-like objects into real arrays:
let arrayLike = { 0: 'tom', 1: '65', 2: 'Male', 3: ['jane','john','Mary'], 'length': 4 } let arr = Array.from(arrayLike) console.log(arr) // ['tom','65','M',['jane','john','Mary']]
So, what if the length attribute in the above code is removed? Practice has proven that the answer will be an empty array of length 0.
Let’s change the code again, that is, it has the length attribute, but the object’s attribute name is no longer of numeric type, but other string types. The code is 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 ]
will find that the result is an array with a length of 4 and all elements are undefined.
It can be seen that to convert an array-like object into a real array, you must have The following conditions:
This type of array object must have a length attribute, which is used to specify the length of the array. If there is no length attribute, the converted array is an empty array.
The attribute name of this type of array object must be a numeric or string number
ps: The attribute name of this type of array object can be quoted or not.
2. Convert the data of the Set structure into a real array:
let arr = [12,45,97,9797,564,134,45642] let set = new Set(arr) console.log(Array.from(set)) // [ 12, 45, 97, 9797, 564, 134, 45642 ]
Array.from
can also accept a second parameter, which acts like the map
method of an array and is used to map Each element is processed and the processed value is placed into the returned array. As follows:
let arr = [12,45,97,9797,564,134,45642] let set = new Set(arr) console.log(Array.from(set, item => item + 1)) // [ 13, 46, 98, 9798, 565, 135, 45643 ]
3. Convert the string to an array:
let str = 'hello world !'; console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", " l", "d", "!"]
4. The Array.from parameter is a real array:
console.log(Array.from([12,45,47,56,213,4654,154]))
like this , Array.from will return an identical new array