数组扁平化—手写flatten

1,346 阅读1分钟

递归的思想

  • 第一种
Array.prototype.flatten = function(){
    var temp = [],ary = this;
    function fn(ary){
         ary.forEach(item=>{
        if(typeof item === 'object'){
            fn(item);
        }else{
            temp.push(item);
        }
     })
    }
    fn(ary);
    return temp;
}
var ary = [1,[2,4],[2,[3,5,6],5],6,7,8]
ary.flatten();//[1, 2, 4, 2, 3, 5, 6, 5, 6, 7, 8]
  • 第二种 Es6(...扩展运算符)加递归
Array.prototype.flatten = function () {
    return [].concat(...this.map(item => 
    Array.isArray(item) ? item.flatten() : [item])));
}

数组的toString方法

Array.prototype.flatten = function(){
    var ary = this;
    ary = ary.toString().split(',').map(item=>+item);
    return ary;
}