1.转成字符串,利用正则的方法

let ary = [1, [2, [3, [4, 5]]], [6, 7, [8, 9, [11, 12]], 10]];  //=>[1,2,3,4,5,6]

let str = JSON.stringify(ary);
//=>第一种处理
// console.log(str);//=>[1,[2,[3,[4,5]]],6]
// ary = str.replace(/(\[|\])/g, '').split(','); //split():用','来分割,返回一个分割之后的数组
// console.log(ary);

//=>第二种处理
str = str.replace(/(\[|\])/g, '');
str = '[' + str + ']';
ary = JSON.parse(str);
console.log(ary);

 

2.利用递归

let result = [],
fn = function (ary) {
  if (ary.length === 0) return;
  for (let i = 0; i < ary.length; i++) {
    let item = ary[i];
    if (typeof item === 'object') {
      fn(item);
    } else {
      result.push(item);
    }
  }
};
fn(ary);
console.log(result);

 

3. ES6 + 递归 (进阶版)

let arr = [[1, 2], 3, [[[4], 5]]]; // 数组展平
let fn = function flatten(arr) {
  return [].concat(
    ...arr.map(x => Array.isArray(x) ? flatten(x) : x)
  )
}
console.log(fn(arr))

 

相关文章:

  • 2021-12-01
  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-13
  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
猜你喜欢
  • 2021-08-23
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
相关资源
相似解决方案