es6—新增的数据类型 数组集合set

版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/82555674

特点:
1.类似于数组,没有重复的元素(唯一的)
2.开发中用于去除重复数据
3.key和value都是相等的

        //创建一个集合
        let set = new Set(['bob', 'lucy', 'john', 'bob', 'lucy']);
        //将重复的元素去除了
        console.log(set);//Set(3) {"bob", "lucy", "john"}


        console.log(Array.from(set));//转换为真数组 (3) ["bob", "lucy", "john"]
        console.log(Array.from(set)[1]);//lucy

一个属性(size)

    {
        let set=new Set(['bob','lucy','john']);
        //类似于length
        console.log(set.size);//3
    }

四个方法
1.add

    {
        let set=new Set(['bob','lucy','john']);
        //添加元素(支持链式调用)
        console.log(set.add('bob2').add('tom'));//Set(5) {"bob", "lucy", "john", "bob2", "tom"}
        console.log(set);//Set(5) {"bob", "lucy", "john", "bob2", "tom"}
    }

2.delete

    {
        let set=new Set(['bob','lucy','john']);
        //删除元素(不支持链式调用)
        console.log(set.delete('bob'));//true
        console.log(set);//Set(2) {"lucy", "john"}
    }

3.has

    {
        let set=new Set(['bob','lucy','john']);
        //判断集合有没有查找元素
        console.log(set.has('bob'));//true
        console.log(set.has('bob1'));//false
    }

4.clear

    {
        let set=new Set(['bob','lucy','john']);
        //清除集合元素
        console.log(set.clear());//undefined
        console.log(set);//Set(0) {}
    }

获取其中元素 keys values entries

    {
        let set=new Set(['bob','lucy','john']);

        console.log(set.keys()); //SetIterator {"bob", "lucy", "john"}
        console.log(set.values()); //SetIterator {"bob", "lucy", "john"}
        console.log(set.entries()); //SetIterator {"bob", "lucy", "john"}

        for(let index of set.keys()){
            console.log(index); //bob; lucy; john
        }
        for(let elem of set.values()){
            console.log(elem); //bob; lucy; john
        }
        for(let [index,elem] of set.entries()){
            console.log(index, elem); //bob bob; lucy lucy; john john;
        }

        for(let index of ['bob','lucy','john'].keys()){
            console.log(index); //0; 1; 2
        }
        for(let elem of ['bob','lucy','john'].values()){
            console.log(elem); //bob; lucy; john
        }
        for(let [index,elem] of ['bob','lucy','john'].entries()){
            console.log(index, elem); //0 "bob"; 1 "lucy"; 2 "john";
        }
    }

猜你喜欢

转载自blog.csdn.net/lucky541788/article/details/82555674