手写flat
let arr = [1,[2,3,[4]],5,6,[7,[8],[9,10,[11],12]]]; Array.prototype.myFlat = function(n){ let newArr = []; this.forEach(item=>{ if(Array.isArray(item) && n > 0){ newArr = newArr.concat(item.myFlat(n-1)) }else{ newArr.push(item) } }) return newArr; } let newArr1 = arr.myFlat(2); let newArr2 = arr.flat(2); console.log(newArr1, newArr2);
青云直上三千码