Home > Article > Web Front-end > What is the usage of flat in es6
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()".
The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.
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.
[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!