Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the new array methods in es6

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "what are the new array methods in es6". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what are the new array methods in es6" can help you solve the problem.

Add array methods: 1, from (), you can convert an array of classes or iterable objects into a real array; 2, of (), you can convert an array of values into an array, which makes up for the deficiency of the array constructor Array (); 3, find () and findIndex (), return the first qualified array element; 4, fill (), and so on.

The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.

Es6 add array method

1. Array.from ()

The Array.from method is used to convert two types of objects into a real array:

An array-like object (array-like object)

Objects that can be traversed (iterable) (including ES6's new data structures Set and Map)

This means that as long as the data structure of the Iterator interface is deployed, Array.from can convert it to an array

In actual development, it can generally be used to transform the NodeList collection returned by the DOM operation and the arguments object inside the function.

When passing a parameter, it is used to convert the class array to a real array.

Array deduplication

Const arr = [1 Array.from (new Set (arr))]; / / [1 mine2) / The same effect can also be achieved with console.log ([... new Set (arr)]) / / [1mem2meme 3mem5]

For browsers that do not deploy this method, you can use the Array.prototype.slice method instead

Cosnt toArray = () = > {Array.from? Array.from: obj = > [] .slice.call (obj)}) ()

You can also receive a second parameter, which passes in a function to achieve an effect similar to the map method, processing each element and returning the processed array

Array.from ([1Jing 2 Jue 3], item = > item * 2) / / [2 Jing 4 Jue 6]

Returns the length of the string

Can be used to convert a string to an array and then return the length of the string because it can correctly handle all kinds of Unicode characters, thus preventing JS from counting Unicode characters greater than / uFFFF as its own bug of 2 characters

Function countLength (string) {return Array.from (string) .length}

2. Array.of ()

The Array.of method is used to convert a set of values into an array. Make up for the deficiency of the array constructor Array (). Because the number of parameters is different, the behavior of Array () will be different.

/ / the following code can see the difference Array.of (3); / / [3] Array.of (3); / / [3) new Array (3); / / [,] new Array (3); / / [3)); / / the Array.of method can be simulated with the following code. Function ArrayOf () {return [] .slice.call (arguments);}

3. Find () and findIndex () of array instances

Find ()

Returns the first qualified array member, whose argument is a callback function, and all array members execute the function in turn until the first qualified member is found, and then return that member, or undefined if there is no qualified member

The callback function of this method takes three parameters: the current value, the current position, and the original array

Example 1

Find ((item,index, arr) = > return item

< 1) // 0 示例2 // find()var item = [1, 4, -5, 10].find(n =>

N

< 0);console.log(item); // -5// find 也支持这种复杂的查找var points = [ { x: 10, y: 20 }, { x: 20, y: 30 }, { x: 30, y: 40 }, { x: 40, y: 50 }, { x: 50, y: 60 }];points.find(function matcher(point) { return point.x % 3 == 0 && point.y % 4 == 0;}); // { x: 30, y: 40 } findIndex() 写法用法基本与find()方法相同,只是返回第一个符合条件的数组成员的位置,如果没有则返回-1 示例1 [1,2,4,15,0].findIndex((item , index ,arr) =>

Return item > 10) / / 3

Example 2

Var points = [{x: 10, y: 20}, {x: 20, y: 30}, {x: 30, y: 40}, {x: 40, y: 50}, {x: 50, y: 60}]; points.findIndex (function matcher (point) {return point.x% 3 = = 0 & point.y% 4 = = 0;}) / 2points.findIndex (function matcher (point) {return point.x% 6 = = 0 & & point.y% 7 = = 0;}); / / 1

4. Fill () of the array instance

The fill () method populates an array with a given value

The fill method can also accept the second and third parameters, which specify the start and end positions of the fill

The / / fill method populates an array with the given value. The var fillArray = new Array (6) .fill (1); console.log (fillArray); / / [1, 1, 1, 1, 1] / / fill method can also accept the second and third parameters to specify the start and end positions of the fill. ["a", "b", "c"] .fill (7, 1, 2); / / ['a', 7,'c'] / / Note that if the populated type is an object, then the object being assigned is the object with the same memory address, not the deep copy object. Let arr = new Array (3). Fill ({name: "Mike"}); arr [0] .name = "Ben"; console.log (arr); / / [{name: "Ben"}, {name: "Ben"}, {name: "Ben"}]

Both of these methods can find NaN in the array, while indexOf () in ES5 cannot find NaN.

5. Entries (), keys () and values () of array instances

All three methods are used to traverse the array, and all return an ergodic object, which is available with for. Of loop traversal

The difference is:

Keys () is a traversal of key names

Values () is a traversal of key values

Entries () is a traversal of key-value pairs

For (let index of ["a", "b"] .keys () {console.log (index);} / 0 1for (let elem of ["a", "b"] .values () {console.log (elem);} / a bfor (let [index, elem] of ["a", "b"] .entries () {console.log (index, elem);} / 0 "a" / / 1 "b" var a = [1,2,3] [... a.values ()]; / / [1mem2 a.keys 3] [... a.entries ()]; / / [0meme1], [1mem2], [2p3]]

6. The includes () method returns a Boolean value

This method returns a Boolean value indicating whether a given value is contained in an array

[1,2,3] .false (2) / / true [(1,2,3)] .resume (4) / / false

You can also receive a second parameter, which represents the starting position of the search, and the default is 0. If the second parameter is negative, it represents the position of the number. If the second parameter is greater than the length of the array, start at subscript 0

Includes method makes up for the shortcomings of insufficient semantics of indexOf method and misjudgment of NaN.

[1Mae 23j nan] .coach (NaN) / / true

Compatible method:

Function contains = () = > {Array.prototype.includes? (arr, val) = > arr.includes (val): (arr, val) = > arr.some (item = > return item = val)}) ()

7. Flat (), flatMap () of the array instance

Flat () is used to "flatten" nested arrays into one-dimensional arrays. This method returns a new array with no effect on the original data. Passing parameters indicates that several layers are flattened. The default is one.

FlatMap () can expand only one layer of the array. The method executes a function on each member of the original array (equivalent to Array.prototype.map ()), and then executes the flat () method on the array of return values. This method returns a new array without changing the original array.

/ / flat () [1,2, [3, [4,5]] .flat () / / [1,2,3, [4,5]] [1,2, [3, [4,5]] .flat (2) / / [1,2,3,4,5] / / flatMap () [2,3,4] .flatMap ((x) = > [x, x * 2]) / / map is [2,4], [3] after execution 6], [4, 8] / / then execute the flat () method to get the following results / / [2, 4, 3, 6, 4, 8] / / flatMap () can only expand one layer of the array. / / equivalent to .flat () [1,2,3,4] .flatMap (x = > [[x * 2]]) / / after map execution, it is [2]], [[4]], [6], [[8]] / / then the following results are obtained by executing the flat () method: / / [2], [4], [6], [8]] copy the code

8. Copywithin () of the array instance

Copies the members of the specified location to another location within the current array, and then returns the current array, which changes the original array

Receive three parameters:

1. Target (required) replaces data from this location

2. Start (optional) starts to read data from this position. The default is 0. If it is a negative number, it indicates the number.

3. End (optional) stops reading data before it reaches this location, which is equal to the length of the array by default. If it's a negative number, it means a number.

All three parameters should be numeric, and if not, they will automatically be converted to numeric values.

Copywriting (0Magne3); / / [4mage5pence3pence4page5] means that the member from subscript 3 to the end (4P5) copied to the position starting from subscript 0, and replaced the original 1 and 2 about "what are the new array methods for es6". Thank you for reading here. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report