ES6——Set对象

Set对象的存储类型为唯一值,这个值与数据类型无关。

set在出现重复值时,自动将重复的值删除。

        <script>
            let mySet=new Set();
            mySet.add(1);
            mySet.add("test");
            mySet.add(3);
            mySet.add(3);
            mySet.add("3");
            mySet.delete("3");
            mySet.forEach(function(value){
                console.log(value);
            });       
        </script>


类型转换

Set与Array的相互转化:

      <script>
            let myArray=["value1","value2","value3"];
            console.log("-----Array to Set----");
            let mySet=new Set(myArray);
            console.log(mySet);
            console.log("-----Set to Array----")
            let myArray1=[...mySet];
            console.log(myArray1);
        </script>


 string 转 Set  (Set不可以通过toString转化为string),

        <script>            
            let mySet=new Set("Happy");
            console.log(mySet);//{"H", "a", "p", "y"}
        </script>

Set对象作用

1.数组去重

2.并集

3.交集

4.差集

        <script>
            let myArray=[1,2,2,3,3,4]
            let mySet=new Set(myArray);
            myArray=[...mySet];
            console.log("---数组去重---");
            console.log(myArray);//(4) [1, 2, 3, 4]
            
            let s1=new Set([1,2,3]);
            let s2=new Set([2,3,4,5]);
 
            console.log("---并集---");
            let unionSet=new Set([...s1,...s2]);
            console.log(unionSet);
 
            console.log("---交集---");
            let intersect=new Set([...s1].filter(x=>s2.has(x)));
            console.log(intersect);//Set(2) {2, 3}
 
            console.log("---差集---");
            let difference=new Set([...s1].filter(x=>!s2.has(x)));
            console.log(difference);//Set(1) {1}
        </script>
发布了452 篇原创文章 · 获赞 83 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/caseywei/article/details/103736570
今日推荐