数组压平(flat)
/**
* 数组压平
*/
const flatByWhile = (arr = [1,[2,4],[4], [43,2,[444,1,[54]]], [22,3,[4]], 32], deep = 1) => { while(arr.some(Array.isArray) && deep > 0){ /** * concat方法会将元素为数组的值解构一次 * arr = [...arr]错误方式 */ arr = [].concat(...arr) deep-- } return arr } const flatByRecursion = (arr = [1,[2,4],[4], [43,2,[444,1,[54]]], [22,3,[4]], 32]) => { let result = [] for(let i = 0; i < arr.length; i++){ const item = arr[i] if(Array.isArray(item) && deep > 0){ result = [...result, ...flat(item, deep)] }else{ result.push(item) } } return result }
添加到原型
Array.prototype.myselfFlat = function(deep = 1) { let origin = this while(origin.some(Array.isArray) && deep > 0){ origin = [].concat(...origin) deep-- } return origin }
以自己现在的努力程度,还没有资格和别人拼天赋