当前位置:网站首页>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));
边栏推荐
猜你喜欢

IJCAI 2022 | 图结构学习最新综述:研究进展与未来展望

SQL server, MySQL master-slave construction, EF core read-write separation code implementation

设计一个支持百万用户的系统

mq的学习

Go language slice vs array panic runtime error index out of range problem solving
![[Guangxi University] information sharing of postgraduate entrance examination and re examination](/img/25/e35de6b9d803c9a80e0d2816aaad87.jpg)
[Guangxi University] information sharing of postgraduate entrance examination and re examination

咸鱼ESP32实例—MQTT 点亮LED

LeetCode - 哈希表专题

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

Opencv4.60 installation and configuration
随机推荐
21天学习挑战赛-《Autosar从入门到精通-实战篇》
ShardingSphere之分库分表概念介绍(二)
Network engineering -- ranking of Chinese universities in Soft Science
Create SSL certificate using OpenSSL
[vscode] vscode usage
C# 倒计时工具
LinkedList内部原理解析
ARouter源码解析(三)
树上启发式合并
Word segmentation results of ES query index fields
(iros 2022) monocular visual inertial odometer based on event camera
Pytorch deep learning practice lesson 9 multi classification problems (handwritten numeral MNIST)
pycharm使用conda调用远程服务器
SD卡介绍(基于SPEC3.0)
这款微信插件太好用了
mq的学习
Retrofit源码解析
MySQL中各类型文件详解
MATLAB的数列与极限运算
Personal blog applet

