Set


Set和Map相比,也有一组key的集合,但不存储value。由于key不能重复,所以,在Set中没有重复的key。

Set构造

要构造一个Set对象,需提供一个Array作为输入,或者直接构造一个空Set,如:

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    var set1 = new Set();
                

add()

add方法可以向set中添加一个元素,如果该元素已经存在,则不再添加。

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    set.add("tianjin");
                    set.add("guangzhou");
                

delete()

delete方法可以将给定的元素在Set中删除

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    set.delete("chongqing"); 
                

has()

通过has方法查询给定的元素是否存在

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    set.has("chongqing"); 
                

set的遍历

除了通过for of 进行遍历,还可以通过迭代器直接进行遍历

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    
                    for (let x of set.values()){
                        console.log(x);
                    }
        
                    var iter = set.values();
                    for (;;){
                        let v = iter.next();
                        if (v.done){
                           break;
                        }
                        console.log(v.value);
                   }
                

clear()

clear方法可以清空set的元素

                    var set = new Set(["beijing","shanghai","tianjin","chongqing"]);
                    set.has("chongqing"); 
                    set.size();  //0
                

本节重点