es6的 set 學習總結

 ================set 集合=======================
        一直以來,JS只能使用數組和對象來保持多個數據,缺乏像其他語言那樣擁有豐富的結合類型
        。因此,ES6 新增了兩種結合類型(set 和 map), 用於不同場景發揮作用。

        1. set 用於存放不能重複的數據
        如何創建一個set:const sets = new Set(); // 創建一個沒有任何內容的set集合
             const contentSet = new Set(iterable); // 創建一個具有初始化內容的set集合,
            內容來自迭代對象每一次迭代的結果,並且自動去重

        2. 如何對set 集合進行後續操作
         add(數據): 添加一個數據到set集合末尾,如果數據已經存在,不存在任何操作
           set 使用Object.js 的方式來判斷兩個數據是否相同, 但是set任務 +0-0 是相等的
         has(數據): 判斷set中是否存在兩個相等的數據
         delete(數據): 刪除匹配的數據,返回是否刪除成功
         clear(): 清空整個set集合


         3. 如何和數組相互轉化
         // 數組使用set來去重
         const s = new Set([1,2,3,4,5,6,7,8]);
         const arr = [...s];

         // 字符串去重
         const str = "fsjfsjsjfifas";
         const s = [...new Set(str)].join("");

         4. 如何遍歷
          1. 由於set是迭代對象的屬性, 可以使用 for of 來遍歷
          2. 使用set內部提供的實例方法, forEach()
          const s = new Set([1,2,3,4,5,6,7,8]);
          s.forEach((item, index, obj) => {
              item: // set中的每一項
              index: // set 不存在下標,爲了保持forEach()的一致, 這個參數和第一個參數一樣
              obj: set 對象

          })
        注意: set中的index 不是下標

        求兩個數組的交集,並集, 差級:
        例如:
            const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
            const arr2 = [1, 3, 4, 5, 6, 3, 6, 7, 9];
            // 求並集
            const s = [...new Set(arr1.concat(arr2))];
            const s1 = [...new Set([...arr1, ...arr2])];
            console.log(s, s1, '並集');

            // 求交集
            const s3 = [...new Set(arr1)].filter(item => {
                return new Set(arr2).has(item);
            })
            const s4 = [...new Set(arr1)].filter(item => arr2.indexOf(item) !== -1)
            console.log(s3, s4, '交集');

            // 求差值
            const s5 = [...new Set([...arr1, ...arr2])].filter(item => (arr1.indexOf(item) !== -1 && arr2.indexOf(item) === -1) || (arr2.indexOf(item) !== -1 && arr1.indexOf(item) === -1));
            const s6 = [...new Set([...arr1, ...arr2])].filter(item => s3.indexOf(item) !== -1);
            console.log(s5, s6, "差值")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章