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 arr15 }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]