思路:
很简单,和我们之前做的数组扁平化差不多,也就多一个传入参数depth 表示要展开的深度,话不多说,直接上代码
(1)直接递归版
let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]// 传入depth参数,默认值为 1Array.prototype._flat = function (depth = 1) {// 当到达指定深度,或 当前对象不是数组时,直接返回这个值if(depth < 1 || !Array.isArray(this)){return this}let res = []for (const item of this) {if (Array.isArray(item)) {res = res.concat(item._flat(depth - 1))} else {res.push(item)}}return res}console.log(arr._flat());console.log(arr._flat(2));console.log(arr._flat(4));
(2)reduce版
let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]Array.prototype._flat = function (depth = 1) {if (depth < 1 || !Array.isArray(this)) {return this}return this.reduce((prev, curr) => {if (Array.isArray(curr)) {return prev.concat(curr._flat(depth - 1))} else {return prev.concat(curr)}}, [])}console.log(arr._flat());console.log(arr._flat(2));console.log(arr._flat(4));
在使用flat时,如何直接全部展开
我们可以直接参考MDN,传入 depth 为 Infinity
let arr = [1, [2, 3], [4, [5, [6, [7, 8]]]]]console.log(arr._flat(Infinity));
使用flat时,数组内的空项会被移除
let arr = [1, 2, , 4, 5];console.log(arr._flat());

关于flat的更多的详情,可以参考MDN-flat
