三:多维数组转为一维数组

将多维数组转为一维数组:

1、使用数组的join( )方法:

const arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]];
const arrString = arr.join();
const arrList = arrString.split(',');
console.log('arrList=', arrList);

2、使用toString( )方法:

const arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]];
const arrString = arr.toString();
let arrList = arrString.split(",");
console.log(arrList);

3、使用es6的flat( )方法:

// es6方法:flat():如果要拉平一维数组则默认为1,拉平二维数组为2...如果要拉平所有的数组为Infinity
const arr = [1, 2, 3, 4, 5, [6, 7, 8, [9, 10, 11, 12, [13, 14, 15, 16]]]];
const arrList1 = arr.flat();
console.log('拉平一维数组:', arrList1);
const arrList2 = arr.flat(2);
console.log('拉平二维数组:', arrList2);
const arrListInfinity = arr.flat(Infinity);
console.log('拉平无限数组:', arrListInfinity);

参考:https://www.cnblogs.com/zhilu/p/13803724.html

原文地址:https://www.cnblogs.com/liumcb/p/14793892.html