What is the usage of flat in es6

WBOY
Release: 2022-03-31 15:55:14
Original
3516 people have browsed it

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()
Copy after login

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)
Copy after login

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
    }
```
Copy after login

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!

Related labels:
es6
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template