-
Notifications
You must be signed in to change notification settings - Fork 151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
数组扁平化 flat 的几种方式 #556
Comments
let arr = [1, 2, [3, 4], [5, 6, [7, 8, 9]]];
/**第一种方式:flat */
let res1 = arr.flat(Infinity);
console.log(res1);
/**第二种方式:join + split*/
let res2 = arr.join().split(',').map(Number);
console.log(res2);
/**第三种方式: toString + split*/
let res3 = arr.toString().split(',').map(Number);
console.log(res3);
/**第四种方式:递归展开 */
const flattern = arr=>{
const res = [];
arr.forEach((item)=>{
if(Array.isArray(item)){
res.push(...flattern(item));
}else{
res.push(item);
}
})
return res;
}
flattern(arr);
/**第五种方式:递归concat */
function flattern2(arr){
return [].concat(
...arr.map(item=>Array.isArray(item)? flattern2(item):item)
)
}
flattern2(arr); |
第二第三种,不符合吧! 展开后 全部转换为 number类型了,如果是其他类型的数组呢? 这样输出会改变数据类型 或者 NaN |
对于当前例子而言采用的就是这几种方式 |
/**第六种方式:while+some遍历 */
|
function flatFun(arr, depth = 1) { |
|
No description provided.
The text was updated successfully, but these errors were encountered: