📌  相关文章
📜  如何在 JavaScript 中将 Set 转换为数组?(1)

📅  最后修改于: 2023-12-03 14:52:20.922000             🧑  作者: Mango

如何在 JavaScript 中将 Set 转换为数组?

在 JavaScript 中,可以使用 Set 类来存储一组唯一的值。但是有时候我们需要将 Set 转换为数组来进行一些操作。

下面提供三种将 Set 转换为数组的方法:

方法一:使用 Array.from()

可以使用 Array.from() 方法将 Set 转换为数组。

const set = new Set([1, 2, 3]);
const array = Array.from(set);
console.log(array); // [1, 2, 3]
方法二:使用展开运算符(Spread Operator)

使用展开运算符(Spread Operator)也可以将 Set 转换为数组。

const set = new Set([1, 2, 3]);
const array = [...set];
console.log(array); // [1, 2, 3]
方法三:使用 Array.prototype.concat()

使用 Array.prototype.concat() 方法也可以将 Set 转换为数组。

const set = new Set([1, 2, 3]);
const array = [].concat(set);
console.log(array); // [1, 2, 3]

以上就是将 Set 转换为数组的三种方法。需要根据自己的需求选择适合自己的方法。