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

How to use the flat method in es6

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to use the flat method in es6, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value, I believe you will have something to gain after reading this es6 article on how to use the flat method. Let's take a look at it.

In es6, the flat () method is used to recursively traverse the array at a specified depth and to merge all elements with the elements of the traversed subarray into a new array return, that is, the array dimensionality reduction, with the syntax "Array.prototype.flat ()".

This tutorial operating environment: windows10 system, ECMAScript version 6. 0, Dell G3 computer.

What is the use of flat in es6? Array.prototype.flat ()

The flat () method recursively traverses the array at a specified depth and merges all elements with the elements in the traversed subarray into a new array.

That's what we call array dimensionality reduction.

Function: flatten the array, loop the value of each item, and if the value of the item is also an array, take it out (equivalent to removing the [] parentheses from the array)

Flat (n)

Flatten the array of each item, n defaults to 1, indicating the flattening depth.

To make a long story short, it is to do an unbracketed operation to Array according to the parameters in flat, which goes to one layer by default.

Let's simply implement it.

````Array.prototype.myFlat = function (num = 1) {if (num

< 1) { return this } const res = [] for (let i = 0; i < this.length; i++) { if (Array.isArray(this[i])) { res.push(...this[i].myFlat(num - 1)) } else { res.push(this[i]) } } return res }``` 思路比较简单,如果是非数组,直接push,如果是数字,需要把它去一层括号进行处理。去N次括号的话,调用N次myFlat方法即可。

This is the end of the article on "how to use the flat method in es6". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use the flat method in es6". If you want to learn more, you are welcome to follow the industry information channel.

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