How can ES6 achieve pseudo arrays conversion to arrays?
In ES6, you can use the Array.from() method to convert array-like objects (such as pseudo arrays) into actual arrays.
Pseudo-arrays are objects that resemble arrays in some ways but lack the methods and properties of arrays. Common examples of pseudo-arrays include the arguments object and DOM NodeList object.
Here is an example code using the Array.from() method to convert a pseudo array into an array:
// 伪数组
var arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
// 将伪数组转换为数组
var array = Array.from(arrayLike);
console.log(array); // ['a', 'b', 'c']
The Array.from() method takes an iterable object as a parameter and returns a new array. It loops through the iterable object and adds each element to the new array one by one.
It should be noted that the Array.from() method can only convert objects with numerical keys and a length property. Therefore, before converting a pseudo-array into an array, make sure the pseudo-array object has the correct keys and length property.
Additionally, if you want to convert a specific type of pseudo-array to an array, you can use the Array.from() method with the second parameter for mapping. For example, converting a DOM NodeList object to an array:
// DOM NodeList对象
var nodeList = document.querySelectorAll('div');
// 将DOM NodeList对象转换为数组
var array = Array.from(nodeList, element => element.textContent);
console.log(array); // 包含了每个div元素的文本内容的数组
In the example above, the second parameter of the Array.from() method is a mapping function that transforms each element into its text content and adds the results to a new array.
In conclusion, the Array.from() method can easily convert array-like objects into arrays, and also allows for element mapping through the second parameter.