美文网首页
js 偏平化数组

js 偏平化数组

作者: RQrry | 来源:发表于2019-08-29 18:37 被阅读0次
    const arr1 = [1,,[2,[3,[4]]]];
    // [1,2,3,4]
    
    const arr2 = [1,[2,[3,[4]]]];
    // [1,2,3,4]
    

    递归

    const flatten = function (arr) {
      var res = [];
      arr.map(v => {
        if (Array.isArray(v)) {
          res = res.concat(flatten(v));
        } else {
          res.push(v);
        }
      })
      return res;
    }
    

    ES6 Array.prototype.flat() 将嵌套数组拉平,返回一个新数组

    const flatten = function (arr) {
      return arr.flat(Infinity);
    }
    

    Array.prototype.join() 将一个数组的所有元素连接成一个字符串

    const flatten = function (arr) {
      return arr.join().split(',').filter(v => v !== '');
    }
    

    相关文章

      网友评论

          本文标题:js 偏平化数组

          本文链接:https://www.haomeiwen.com/subject/fikwectx.html