【ES6】Set数据结构

76 阅读2分钟

一、Set

Set类似数组,但是成员的值是唯一的,没有重复的值。Set本身是一个构造函数,用来生成Set数据结构。Set函数可以接受一个数组(或者具有Iterable接口的其他数据结构)作为参数,用来初始化。

1、数组去重

let s=new Set([1,2,3,1,2,3])
console.log(s);//Set(3) [ 1, 2, 3 ]

2、字符串去重

let s=new Set([..."aabbcc"])
console.log(s);//Set(3) [ "a", "b", "c" ]

3、两个NaN或空对象都视为不同

console.log(new Set("NaN")===new Set("NaN"));//false
console.log(new Set([{}])===new Set([{}]));//false

二、Set的属性

1、获取Set成员总数 set.size

let s=new Set([1,2,3,4,5])
console.log(s.size);

2、获取Set的构造函数

let s=new Set([1,2,3,4,5])
console.log(s.constructor);//function Set()

三、Set的方法

1、操作方法

(1)添加成员 set.add(value)

    let s= new Set(["x","y","z"])
    s.add("我是新添的成员k")
    console.log(s);//Set(4) [ "x", "y", "z", "我是新添的成员k" ]

(2)删除成员 set.delete(value)

    let s= new Set(["x","y","z"])
    s.delete("x")
    console.log(s);//Set [ "y", "z" ]

(3)判断某成员是否存在 set.has(value)

    let s= new Set(["x","y","z"])
    console.log(s.has("x"));//true
    console.log(s.has("k"));//false

(4)清空所有成员 set.clear()

    let s= new Set(["x","y","z"])
    s.clear()
    console.log(s);//Set []

2、遍历方法

(1)for(of set.keys())

    let s = new Set(["x","y","z"])
   for (let i of s.keys()){
    console.log(i);
   }
   //x
   //y
   //z

(2)for(of set.values())

    let s = new Set(["x","y","z"])
   for (let i of s.values()){
    console.log(i);
   }
   //x
   //y
   //z
   

等价于

   let s = new Set(["x","y","z"])
   for (let i of s){
    console.log(i);
   }
   //x
   //y
   //z

(3)for(of set.entries())

    let s = new Set(["x","y","z"])
   for (let i of s.entries()){
    console.log(i);
   }
   //Array [ "x", "x" ]
   //Array [ "y", "y" ]
   //Array [ "z", "z" ]

(4)set.foEach()

    let s = new Set(["a", "b", "c"])
    s.forEach((key, value) => (console.log("key=", key, "value=", value)))
    //key= a value= a 
    //key= b value= b 
    //key= c value= c

3、遍历的应用

(1)数组去重:扩展运算符+Set

    let arr =[1,2,3,1,2,3]
    console.log([...new Set(arr)]);//Array(3) [ 1, 2, 3 ]

(2)获取两个数组的并集、交集、差集。

    let a = new Set([1, 2, 3, 4])
    let b = new Set([2, 3, 4, 5])
    console.log("并集:",new Set([...a,...b]));
    //并集:Set(5) [ 1, 2, 3, 4, 5 ]
    console.log("交集:",new Set([...a].filter(item=>b.has(item))));
    //交集:Set(3) [ 2, 3, 4 ]
    console.log("差集:",new Set([...a].filter(item=>!b.has(item))));
    //差集:Set(1) [ 1 ]