多维数组=>一维数组
let ary = [1, [2, [3, [4, 5]]], 6];
let str = JSON.stringify(ary);
//第一种处理
ary = str.replace(/(\[\]))/g, '').split(',');
//第二种处理
str = str.replace(/(\[\]))/g, '');
str = '[' + str + ']';
ary = JSON.parse(str);
//第三次:递归处理
let result = [];
let fn = function(ary) {
for(let i = 0; i < ary.length; i++) }{
let item = ary[i];
if (typeof item === 'object'){
fn(item);
} else {
result.push(item);
}
}
}
第四种方法:用 reduce 实现数组的 flat 方法
```js
Array.prototype.MyFlat = function(depth = 1) {
let arr = Array.prototype.slice.call(this)
if(depth === 0) return arr
return arr.reduce((pre, cur) => {
if (Array.isArray(cur)) {
return [...pre, ...Array.prototype.MyFlat.call(cur, depth-1)]
} else {
return [...pre, cur]
}
}, [])
}
let arr = [1, 2, [3, 4], [5, [6, 7]]]
console.log(arr.MyFlat(Infinity))