Set 集合

  • Set
    • Set对象是值的集合,你可以按照插入的顺序迭代它的元素。 Set中的元素只会出现一次,即 Set 中的元素是唯一的
        let mySet = new Set()
        let obj = {
            a : 1,
            b : 2
        }
    
        mySet.add(obj) 
        mySet.add({
            a : 1,
            b : 2
        }) //虽然与 obj 字面量相同,但是内存地址不同
        mySet.add(1)
        mySet.add(1)
        mySet.add(null)
        mySet.add(NaN)
        mySet.add(NaN)
    
        console.log(mySet.size)
        console.log(mySet.has(1))
        console.log(mySet.has(null))
        console.log(mySet.has(3))
        console.log('删除:' + mySet.delete(NaN))
        console.log(mySet)
        mySet.clear()
        console.log(mySet)
    
        /*
        5
        true
        true
        false
        删除:true
        Set { { a: 1, b: 2 }, { a: 1, b: 2 }, 1, null }
        Set {}
        */
    
    • 方法
      • Array转换成Set实现数组去重
          const arr = [1,1,2,3,4,5,2,6,4,5,6]
          const mySet = new Set(arr)
      
          console.log(mySet)
      
      • Set转换成Array,即可使用数组方法
          [...mySet].reverse()
      
      • forEach()遍历
          mySet.forEach((value, index, arr) => {
              console.log(value, index, arr)
          })
      
      • 求交集
      function getIntersection(arr1, arr2) {
          const set1 = new Set(arr1)
          const set2 = new Set(arr2)
      
          return [...set1].filter(item => set2.has(item))
      }
      
      • 求差集
          function getDifference(arr1, arr2) {
              const set1 = new Set(arr1)
              const set2 = new Set(arr2)
      
              return [...set1].filter(item => !set2.has(item))
          }
      
      • 判断是否是子集
          function isSuperset(arr1, arr2) {
          const set = new Set(arr1)
          const subset = new Set(arr2)
      
          for (let elem of subset) {
              if (!set.has(elem)) {
                  return false;
              }
          }
          return true;
      }
      
      • 求合集
          function getUnion(arr1, arr2){
          const union = new Set(arr1)
      
          arr2.map(item => union.add(item))
      
          return [...union]
      
      • 字符串相关
        • 大小写敏感
          console.log(new Set('hello zEd!'))
          console.log(new Set('hello zed!'))
      
          // Set { 'h', 'e', 'l', 'o', ' ', 'z', 'E', 'd', '!' }
          // Set { 'h', 'e', 'l', 'o', ' ', 'z', 'd', '!' }
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值