//使用强制类型转换
function myFlatter1(arr=[]) {
if(typeof arr[0] === 'number'){
return arr.toLocaleString().split(',').map((item)=>Number(item));
}else{
return arr.toLocaleString().split(',');
}
}
//使用JSON.striify.parse加正则去[]
function myFlatter2(arr=[]) {
let result = JSON.stringify(arr);
result = result.replace(/(\[|\])/g,'');
result = '[' + result + ']';
return JSON.parse(result);
}
//使用while循环+findeIndex+展开运算符...
function myFlatter3(arr=[]){
while(arr.findIndex((item)=>Array.isArray(item))>0){
arr = [].concat(...arr);
}
return arr;
}
//使用reduce()+递归
function myFlatter4(arr = []){
return arr.reduce((pre,current, currentIndex, arr)=>{
if(Array.isArray(current)){
return pre.concat(myFlatter4(current));
}else{
return pre.concat(current);
}
}, []);
}
const arr1 = [1,2,[3,4,4],5];
const arr2 = ['果',['子',['我','爱','你'],'极'],'了'];
console.log(myFlatter1(arr1));
console.log(myFlatter1(arr2));
console.log(myFlatter2(arr1));
console.log(myFlatter2(arr2));
console.log(myFlatter3(arr1));
console.log(myFlatter3(arr2));
console.log(myFlatter4(arr1));
console.log(myFlatter4(arr2));
console