/**
* 手写flat
* @param {*} depth 层级数
* @returns 扁平化后的数组
*/
Function.prototype.myFlat = function (depth) {
// 当扁平化的层次小于等于0时,返回原数组
if (!Number(depth) || depth <= 0) {
return this;
}
// 保存被扁平化的数组
let _arr = this;
// 保存结果
let result = [];
// 只有当depth大于0时,继续递归处理
if (depth > 0) {
result = _arr.reduce(
(pre, cur) => pre.concat(Array.isArray(cur) ? cur.myFlat(--depth) : cur),
[]
);
}
return result;
};