JS 模拟 Array.prototype.flat

简易模拟数组的 flat 方法

复制代码
 1 /**
 2  * 将一个输入转为合理的整数
 3  */
 4 const toInterger = val => {
 5   const num = Number(val);
 6   if (Number.isNaN(num)) return 0;
 7   if (num === 0 || !Number.isFinite(num)) return num;
 8   return (num > 0 ? 1 : -1) * Math.floor(Math.abs(num));
 9 };
10 
11 /**
12  * 获取一个合法的长度值
13  */
14 const toLength = val => {
15   const ite = toInterger(val);
16   return Math.min(Math.max(ite, 0), Math.pow(2, 32) - 1);
17 };
18 
19 Array.prototype._flat = function() {
20   const depth = typeof arguments[0] === 'undefined' ? 1 : toLength(arguments[0]);
21   const result = [];
22   const forEach = result.forEach;
23   const flatDeep = function(a, d) {
24     forEach.call(a, function(val) {
25       if (d > 0 && Array.isArray(val)) {
26         flatDeep(val, d - 1);
27       } else {
28         result.push(val);
29       }
30     });
31   };
32 
33   flatDeep(this, depth);
34 
35   return result;
36 };
复制代码

 

posted @   樊顺  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示