1、Set定义

Set数据结构类似于数组,但它成员是唯一不重复的,常用Set定义:

  1. <script>
  2. const arrays = [1,2,3,4,5,6,7];
  3. arrays.push(8);
  4. arrays.push(1);
  5. const set = new Set();
  6. arrays.forEach(item=>{
  7. set.add(item);
  8. });
  9. const set2 = new Set(arrays);
  10. console.log(set2);
  11. const set3 = new Set([1,2,3,4,5,6,7,8]);
  12. console.log(set3);
  13. const setStr = new Set("abcdefg");
  14. console.log(setStr);
  15. </script>

2、Set属性

  1. <script>
  2. const setStr = new Set("aabbccddeeffgg");
  3. console.log(setStr.size); //size返回成员总数
  4. </script>

3、Set方法

  1. <script>
  2. const setStr = new Set("aabbccddeeffgg");
  3. setStr.add("aaa"); //添加元素
  4. setStr.delete("a"); //删除元素
  5. console.log(setStr.has("b")); //是否包含某个元素
  6. setStr.clear(); //清除元素
  7. console.log(setStr);
  8. </script>

4、Set扩展

  1. <script>
  2. const set3 = new Set([1, 2, 3, 4, 5, 6, 7, 8]);
  3. console.log(set3);
  4. console.log(...set3);
  5. console.log([...set3]);
  6. </script>

5、set对字符串去重

  1. <script>
  2. const setStr = new Set("aabbccddeeffgg");
  3. var str = [...setStr].join("");
  4. console.log(str);
  5. </script>