意思就是:将一个多维数组变为一个一维数组
例子:const arr = [1, [2, [3, [4, 5]]], 6];
结果:[1,2,3,4,5,6]
第一种:使用flat() Infinity 作为深度,展开任意深度的嵌套数组
arr.flat(Infinity)
第二种:reduce
const flatten = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flatten(cur) : cur);
}, [])
}
flatten(arr);
第三种:函数递归
const res = [];
const fn = arr => {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fn(arr[i]);
} else {
res.push(arr[i]);
}
}
}
fn(arr);
之后的几种方法查的。。。
第四种:利用正则
const res = JSON.stringify(arr).replace(/[|]/g, '').split(','); //但数据类型都会变为字符串
第五种:正则改良版本
const res = JSON.parse('[' + JSON.stringify(arr).replace(/[|]/g, '') + ']');