数组扁平化:(多维数组 -> 一维数组)

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))

猜你喜欢

转载自www.cnblogs.com/MrZhujl/p/13174497.html