1. 使用flag方法

  1. console.log(arr.flat(Infinity)); // 使用 flat方法 设置其参数为Infinity

2. 使用递归+for循环

  1. let arr = [22, 23, 32, [23, 231, [32, [23], 23], [2]]]
  2. // console.log(arr.flat(Infinity)); // 使用 flat方法 设置其参数为Infinity
  3. // 使用递归+for循环的方法
  4. function dimensionalityReduction(arr) {
  5. let result = [];
  6. for (let i = 0; i < arr.length; i++) {
  7. if (Array.isArray(arr[i])) {
  8. result = result.concat(dimensionalityReduction(arr[i]));
  9. } else {
  10. result.push(arr[i]);
  11. }
  12. }
  13. return result;
  14. }
  15. console.log(dimensionalityReduction(arr));

3. 使用reduce+递归

  1. function flatten(arr) {
  2. // 使用reduce高阶函数 实现 多维数组的降维处理
  3. return arr.reduce((a, b) => {
  4. return a.concat(typeof b === "object" ? flatten(b) : b)
  5. }, [])
  6. }

4. 使用toString的方法

  1. function flatten(arr) {
  2. return arr.toString().split(',').map(x=>Number(x))
  3. }
  4. console.log(flatten(arr)); // [22, 23, 32, 23, 231, 32, 23, 23, 2]

5. 使用扩展运算符…

  1. // 使用扩展运算符的方法 还有一个some方法 只要有满足条件的就返回true 继续执行
  2. function flatten(arr) {
  3. console.log(arr.some(x => typeof x === "object"));
  4. while (arr.some(x => typeof x === "object")) {
  5. console.log(...arr);
  6. arr = [].concat(...arr)
  7. }
  8. return arr
  9. }
  10. console.log(flatten(arr));

6. 使用正则+split方法 /字符串的拼接

  1. // 使用正则的方式
  2. function flatten(arr) {
  3. return arr.toString().replace(/[\[\]]*/g, '').split(',').map(x => Number(x))
  4. }
  5. console.log(flatten(arr));