Array flat的实现


 1 if (!Array.prototype.flat) {
 2     Array.prototype.flat = function (num = 1) {
 3         if (!Number(num) || Number(num) < 0) {
 4             return this;
 5         }
 6         var arr = []
 7         this.forEach((item) => {
 8             if (Array.isArray(item)) {
 9                 arr = arr.concat(item.flat(--num))
10             } else {
11                 arr.push(item)
12             }
13         })
14         return arr
15     }
16 }

测试用例

 1 const arr = [1, [2, [3, 'a', [4]]]]
 2 
 3 console.log(arr.flat('dsdsadf'));  // [1, [2, [3, 'a', [4]]]]
 4 console.log(arr.flat(-32)); // [1, [2, [3, 'a', [4]]]]
 5 console.log(arr.flat(0));   // [1, [2, [3, 'a', [4]]]]
 6 console.log(arr.flat('1'));   // [1, 2, [3, 'a', [4]]]
 7 console.log(arr.flat('2'));    // [1, 2, 3, 'a', [4]]
 8 console.log(arr.flat(3));       // [1, 2, 3, 'a', 4]
 9 console.log(arr.flat(Infinity));     // [1, 2, 3, 'a', 4]
10 console.log(arr.flat('Infinity'));   // [1, 2, 3, 'a', 4]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM