当前位置:网站首页>JS提升:实现flat平铺的底层原理
JS提升:实现flat平铺的底层原理
2022-07-28 09:18:00 【The..Fuir】
以下这些方法你得熟悉reduce方法和some方法
方法一:
let arr=[1,2,3,[4,5],[6,7,[8,9,[10]]]] function flat(arr,depth){ if(depth<=0){ return arr; } return arr.reduce((pre,cur)=>{ if(Array.isArray(cur)){ return pre.concat(flat(cur,depth-1)); } return pre.concat(cur); },[]) } console.log(flat(arr,3));
方法二:
let arr=[1,2,3,[4,5],[6,7,[8,9,[10]]]] function flat(arr,depth){ return depth ===0 ? arr :arr.reduce((pre,cur)=>Array.isArray(cur) ? pre.concat(flat(cur,depth-1) ): pre.concat(cur),[]) } console.log(flat(arr,2));方法三:
let arr=[1,2,3,[4,5],[6,7,[8,9,[10]]]] function flat(dep,array){ while(dep){ array=array.reduce((pre,cur)=>{ if(Array.isArray(cur)){ pre.push(...cur); }else{ pre.push(cur); } return pre; },[]); --dep; } return array; } console.log(flat(2,arr));方法四:
let arr=[1,2,3,[4,5],[6,7,[8,9,[10]]]] Array.prototype.flat=function(depth){ let originSource=[...this]; while(depth){ if(originSource.some(item=>Array.isArray(item))){ originSource=[].concat(...originSource); console.log(originSource); } depth--; } return originSource; } console.log(arr.flat(3));
边栏推荐
猜你喜欢

3分钟告诉你如何成为一名黑客|零基础到黑客入门指南,你只需要掌握这五点能力

时序分析41 - 时序预测 TBATS模型

业务可视化-让你的流程图'Run'起来(4.实际业务场景测试)

IJCAI 2022 | the latest overview of graph structure learning: research progress and future prospects

Regular expressions for positive and negative values

力扣376-摆动序列——贪心

C# 倒计时工具

Basic operation of MATLAB

Business visualization - make your flowchart'run'(4. Actual business scenario test)

软件测试与质量学习笔记2----黑盒测试
随机推荐
ARouter源码解析(一)
ARouter源码解析(三)
Arouter source code analysis (II)
mq的学习
Go language slice vs array panic runtime error index out of range problem solving
多线程一定能优化程序性能吗?
ECCV 2022 | can be promoted without fine adjustment! Registration based anomaly detection framework for small samples
设计一个支持百万用户的系统
How promise instance solves hell callback
译文推荐 | 调试 BookKeeper 协议 - 无界 Ledger
OSS直连上传-Rails服务实践
网络工程——软科中国大学专业排名
View事件分发机制源码解析
What is cross domain? How to solve the cross domain problem?
数据库高级学习笔记--系统包
Symbolic operation of MATLAB
数据库核心体系
常用工具函数 持续更新
C# 之 方法参数传递机制
Window source code analysis (IV): window deletion mechanism

