温馨提示×

es6多维数组怎么转化为一维数组

es6
小亿
127
2024-01-11 23:30:11
栏目: 编程语言

在ES6中,可以使用扩展运算符(spread operator)和Array.prototype.concat()方法来将多维数组转化为一维数组。

使用扩展运算符:

const multidimensionalArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = [].concat(...multidimensionalArray);
console.log(flattenedArray);
// Output: [1, 2, 3, 4, 5, 6]

使用Array.prototype.concat()方法:

const multidimensionalArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = [].concat.apply([], multidimensionalArray);
console.log(flattenedArray);
// Output: [1, 2, 3, 4, 5, 6]

这两种方法都可以将多维数组的所有元素合并为一个新的一维数组。

0