1. 使用flag方法
console.log(arr.flat(Infinity)); // 使用 flat方法 设置其参数为Infinity
2. 使用递归+for循环
let arr = [22, 23, 32, [23, 231, [32, [23], 23], [2]]]
// console.log(arr.flat(Infinity)); // 使用 flat方法 设置其参数为Infinity
// 使用递归+for循环的方法
function dimensionalityReduction(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(dimensionalityReduction(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(dimensionalityReduction(arr));
3. 使用reduce+递归
function flatten(arr) {
// 使用reduce高阶函数 实现 多维数组的降维处理
return arr.reduce((a, b) => {
return a.concat(typeof b === "object" ? flatten(b) : b)
}, [])
}
4. 使用toString的方法
function flatten(arr) {
return arr.toString().split(',').map(x=>Number(x))
}
console.log(flatten(arr)); // [22, 23, 32, 23, 231, 32, 23, 23, 2]
5. 使用扩展运算符…
// 使用扩展运算符的方法 还有一个some方法 只要有满足条件的就返回true 继续执行
function flatten(arr) {
console.log(arr.some(x => typeof x === "object"));
while (arr.some(x => typeof x === "object")) {
console.log(...arr);
arr = [].concat(...arr)
}
return arr
}
console.log(flatten(arr));
6. 使用正则+split方法 /字符串的拼接
// 使用正则的方式
function flatten(arr) {
return arr.toString().replace(/[\[\]]*/g, '').split(',').map(x => Number(x))
}
console.log(flatten(arr));