1.利用数组的join()方法:
let arr = [1,2,[3,4,[5,6]]];
console.log(arr.join(',')); //1,2,3,4,5,6
let newArr = arr.join(',').split(',');
console.log(newArr) //["1", "2", "3", "4", "5", "6"]
2.利用toString()方法:
let arr = [1,2,[3,4,[5,6]]];
console.log(arr.toString()) //1,2,3,4,5,6
let newArr = arr.toString().split(',')
console.log(newArr) //["1", "2", "3", "4", "5", "6"]
3.利用es6的flat():
let arr = [1,2,[3,4,[5,6]]];
let newArr = arr.flat(Infinity)//可以输入数字代表扁平化基层,默认1层,Infinity表示无限层
console.log(newArr) //["1", "2", "3", "4", "5", "6"]
4.利用递归:
let arr = [1,2,[3,4,[5,6]]];
let newArr = [];
function delayeringArr(arr){
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
delayeringArr(arr[i])
} else {
newArr.push(arr[i])
}
}
}
delayeringArr(arr)
console.log(newArr) //[1, 2, 3, 4, 5, 6]