// 将 Set 转换为 Array 的示例代码
// 创建一个 Set
const mySet = new Set([1, 2, 3, 4, 5]);
// 方法一:使用 Spread 运算符
const arrayFromSet1 = [...mySet];
console.log(arrayFromSet1); // 输出: [1, 2, 3, 4, 5]
// 方法二:使用 Array.from() 方法
const arrayFromSet2 = Array.from(mySet);
console.log(arrayFromSet2); // 输出: [1, 2, 3, 4, 5]
Set
对象。[...mySet]
,我们可以将 Set
中的所有元素展开并放入一个新的数组中。Array.from()
是一个静态方法,它可以将类似数组的对象或可迭代对象(如 Set
)转换为数组。这两种方法都可以有效地将 Set
转换为数组。
上一篇:js set 遍历
下一篇:js splice用法问题
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站