Summarize several methods of converting array-like objects into real arrays in JavaScript

Summarize several methods of converting array-like objects into real arrays in JavaScript

The common array-like objects basically have the following types:

let arrayLike ={
    
    
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length :3
}           
// 这种类数组是未定义遍历接口的对象

const oDiv = document.querySelectorAll('div'); // 定义了遍历器接口的对象


Another kind of array is the argument object inside the function

argumentsThe object is not one Array. It is similar Array, but does not have any Arrayattributes other than the length attribute and the index element

How to write in ES5

var arr1 = [].slice.call(obj);

var arr2 = [].slice.call(obj);

var arr3 = Array.prototype.slice.call(obj);

New methods in ES6

The Array.from method is used to convert array-like objects and traversable objects into real arrays

As long as the data structure of the Iterator (traversal) interface is deployed, Array.from can convert it into a real array

const arr = Array.from(obj);

Unavailable for objects that are not scheduled to traverse the interface

const arr4 = Array.from(arrayLike)
console.log(arr4) 
// TypeError: object is not iterable 

ES6 extended operator

const args = [...arguments];
const arr5 = [...oDiv];

Unavailable for objects that are not scheduled to traverse the interface

const arr6 = [...arrayLike]
console.log(arr2);  // TypeError: object is not iterable 

Array.of() (additional addition)

This method can convert a set of values ​​into an array

Array.of(12,33,53) //[12,33,53]

The main purpose of adding this method is: to make up for the shortcomings of the array constructor Array(), because the difference in the number of parameters will cause the difference in the behavior of Array()

Array.of can basically be used instead of Array() or new Array(), and there is no overloading due to different parameters, and the behavior is very uniform

References:
[1] Ruan Yifeng. "Introduction to ES6 Standards (Second Edition)" [M]. Beijing. Electronic Industry Press. 2015

Guess you like

Origin blog.csdn.net/qq_43377853/article/details/109706303