JavaScript/set

来自康健生活
Kangkk​(留言 | 贡献)2026年11月26日 (四) 08:25的版本 (文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

标题文字

创建

new Set(['foo', 1, true, {}, undefined, function (){}]);
Set(6) {'foo', 1, true, {…}, undefined, …}
  [[Entries]]
    0: "foo"
      value: "foo"
    1: 1
      value: 1
    2: true
      value: true
    3: 
      value:
        [[Prototype]]: Object
    4: undefined
      value: undefined
    5: function (){}
    size: 6
    [[Prototype]]: Set

方法

add

const _set = new Set();
_set.add(1).add(2).add(3);
console.log(Array.from(_set));
[ 1, 2, 3 ]

格式转换

set 转 array

const _set = new Set([1, 2, 3]);
console.log(Array.from(_set));
[ 1, 2, 3 ]