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 @ 2022-02-26 15:10  樊顺  阅读(52)  评论(0编辑  收藏  举报