es6将二维多维数组转化为一维数组

扁平化数组 Array.prototype.flat()方法

使用方法总结

1. Array.prototype.flat() 用于将嵌套的数组“拉平”,变成一维的数组。该方法返回一个新数组,对原数据没有影响。

 const abc = [1, 2, [3, 4,]]
 console.log(abc.flat()) // [ 1, 2 ,3 ,4 ]

2. 不传参数时,默认“拉平”一层,可以传入一个整数,表示想要“拉平”的层数。

const abc = [1, 2, [3, 4, [5, 6, 7]]]
console.log(abc.flat(2)) //  [1, 2, 3, 4, 5, 6, 7]

3. Infinity 关键字作为参数时,无论多少层嵌套,都会转为一维数组。

const abc = [1, 2, [3, 4, [5, 6, 7], [8, 9]]]
console.log(abc.flat(Infinity))  // [1, 2, 3, 4, 5, 6, 7, 8, 9]

4. 如果原数组有空位,Array.prototype.flat() 会跳过空位。

 const abc = [1, 2, , [3, 4,]]
 console.log(abc.flat()) // [ 1, 2 , 3 , 4 ]

你可能感兴趣的:(vue.js,es6,javascript)