Home  >  Article  >  Web Front-end  >  What is the usage of flat in es6

What is the usage of flat in es6

WBOY
WBOYOriginal
2022-03-31 15:52:483508browse

In es6, the flat() method is used to recursively traverse the array according to a specifiable depth, and merge all elements with the elements of the traversed sub-array into a new array and return it, that is, the array is lowered Dimension, the syntax is "Array.prototype.flat()".

What is the usage of flat in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

What is the usage of flat in es6

Array.prototype.flat()

The flat() method will recursively traverse the array according to a specifiable depth and merge all elements with the elements in the traversed sub-array into A new array is returned.

This is what we call array dimensionality reduction.

Function: Flatten the array and loop through the value of each item. If the value of the item is also an array, take it out (equivalent to removing the [] brackets of 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 perform a parenthesis removal operation on the Array according to the parameters in flat, and the default is to go to one level .

The following is a simple implementation

```
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
    }
```

The idea is relatively simple. If it is a non-array, push it directly. If it is a number, it needs to be processed with a layer of brackets. If you want to remove brackets N times, just call the myFlat method N times.

What is the usage of flat in es6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What is the usage of flat in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn