Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-04-18) 阅读数 9 #程序编程
文章标签 es6

在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]

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门