Three ways to convert non-arrays to arrays in ES6

 

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

We often want to use array methods, such as forEach, filter, or etc. someto deal with non-array data types, then in these scenarios, we need to convert non-arrays to arrays, and three new array conversion methods have been added in ES6 , respectively ** Array.form()**, Array.of() and the spread operator , the three conversion methods have different conversion objects, let's take a look at them separately.

Array.from()

The conversion array method Array.from()can convert the object into a real array. There are two types of objects, namely: array-like objects and objects containing iterators

Array-like object conversion instance

The expression form of the array-like object is an object form with 0, 1 number as the key, and after conversion Array.from(), its value will be converted into an array form

let arrObj = {
  "0": "猪痞恶霸",
  "1": "fzf404",
  length:2
};
let arr = Array.from(arrObj);
console.log(arr); // ['猪痞恶霸', 'fzf404']
复制代码

As above, we define an arrObjarray-like object, and Array.from()convert it into an array through the conversion method ['猪痞恶霸', 'fzf404'].

Readers may read here and want to say: What is the use of converting to an array, can't it be optical syntax, then let's look at the real practical application of converting an array-like object into an array.

Array-like object conversion application

In development, we will use the node list to operate the DOM. By document.querySelectorAll()obtaining it, as shown in the figure below, we can clearly understand that the node list we get is an array-like object, so some methods of the array cannot be used directly, for example, forEachor filteretc.

So you need to use Array.form()the method to convert it to a real array, and then use the array method to perform some additional operations

Contains an iterator object conversion instance

Array.form()You can also convert objects containing iterators into real arrays, such as strings, mapor set, let's take a look at its use

let str = "猪痞恶霸"
let strArr = Array.from(str)
console.log(strArray) // [ '猪', '痞', '恶', '霸' ]
复制代码

Take a string as an example. After being converted into an array, each element corresponds to each character of the string. We used to worry about cutting the string, but we need to use regular cuts. Now only one line of code is needed to complete the separation of the string Array.from(str).

I won’t give any examples of the application here. The essence of the conversion array application is to better use the array method to manipulate and process data, and Array.fromthere is a second parameter

The second parameter of Array.from()

The second parameter is more like an array mapmethod, as a callback function to process each element of the converted data

let str = "猪痞恶霸"
let _str = Array.form(str, (item) => {
    return item+item
})
console.log(_str) // [ '猪猪', '痞痞', '恶恶', '霸霸' ]
复制代码

In the above operation, I simulated the processing of strings, and regular strings can often be used to process strings. Of course, this can be associated with the fact that we can use this method to process user input and also prevent malicious input.

The above is the method of converting an array-like object or an object containing an iterator into an array Array.from(). Let's look at the second method below.Array.of

Array.of()

Array.of()A set of values ​​​​can be converted into an array. In fact, his real practical application is to initialize the array.

let arr = Array(1,2,3)
console.log(arr) // [ 1, 2, 3 ]
复制代码

People who know it will say: Isn't it there Array(), why use it extravagantly Array.of()?

In fact Array.of(), the appearance is not accidental, it makes up for Array()the deficiency of being an array constructor

let arr = new Array(3)
console.log(arr) // [ <3 empty items> ]
复制代码

As above, only pass in the array 3that is obtained as a parameter , and when we pass in 3 or more parameters, the constructed array is different from passing in less than 3, that is to say, the constructed array is not Unite[ <3 empty items> ][,,,]Array

let arr = new Array(3, 2, 1);
console.log(arr); // [ 3, 2, 1 ]
复制代码

That's why you use Array.of()insteadArray

After looking at these two methods of converting arrays directly using arrays, let's look at how to use the spread operator to convert arrays

spread operator

Objects containing iterators can be converted into real arrays by using the extension operator, such as node lists, or array-like objects. The so-called node lists often get the dom list when we use dom operations and then convert it into an array, which is convenient Use some nice array methods.

let domlist = document.querySelectorAll('div');
let arr = [...domlist]
复制代码

An array-like object must contain an iterator before it can be converted using this method. If it does not contain it, it can be Array.from()converted using

let objArr = {
    '0':'hogskin',
    '1':'猪痞恶霸'
}
console.log([...objArr]) // objArr is not iterable
复制代码

mapYou can also setuse this method to convert, of course, the generator function can also be used, because it returns a traverser object, which contains the iterator

at last

That’s all for the three ES6 methods of converting arrays. Welcome to pay attention to my JS advanced column. I am a bully and a front-end student who is determined to be a schoolgirl.

 

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/130614313