flat() 方法的语法:
参数可选:[depth]
depth 参数指定该方法使数组结构平坦的深度,它默认为 1
例子1:两层数组转为一层
const numbers = [1, 2, [3, 4, 5]];
const flatNumbers = numbers.flat();
console.log(flatNumbers);
例子2:三层数组转为一层
const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);
console.log(flatNumbers);
例子3:多层数组转为一层
// 不定深度的数组转为一层数组
// 参数为Infinity
const numbers = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];
const flatNumbers = numbers.flat(Infinity);
console.log(flatNumbers);