模拟方法:Array.prototype.flat(...)
Array.prototype.flat()
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
参数: depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。
返回值: 一个包含将数组与子数组中所有元素的新数组。
——摘自MDN
模拟一:
Array.prototype.myflat = function (depth) { if(depth === 0) return this; let arr = []; this.forEach(item => { if(Array.isArray(item)) { arr = arr.concat(item); } else { arr.push(item); } }) return this.myflat.call(arr, depth-1); }
模拟二:
Array.prototype.myflat = function (depth) { if(depth === 0) return this; return this.myflat.call([].concat(...this), depth-1); }

浙公网安备 33010602011771号