zoukankan      html  css  js  c++  java
  • es6 Set数据结构

    原文    http://es6.ruanyifeng.com/#docs/set-map

    Set类似于数组,但是成员的值都是唯一的,没有重复的值。

    Set 本身是一个构造函数,用来生成 Set 数据结构。

    const s = new Set();
    
    [2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
    
    for (let i of s) {
      console.log(i);
    }
    // 2 3 5 4

    上面代码通过add方法向 Set 结构加入成员,结果表明 Set 结构不会添加重复的值。

    // 例一
    const set = new Set([1, 2, 3, 4, 4]);
    [...set]
    // [1, 2, 3, 4]
    
    // 例二
    const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
    items.size // 5
    
    // 例三
    function divs () {
      return [...document.querySelectorAll('div')];
    }
    
    const set = new Set(divs());
    set.size // 56
    
    // 类似于
    divs().forEach(div => set.add(div));
    set.size // 56

    上面代码中,例一和例二都是Set函数接受数组作为参数,例三是接受类似数组的对象作为参数。

    上面代码中,也展示了一种去除数组重复成员的方法。

    // 去除数组的重复成员
    [...new Set(array)]

    Array.from方法可以将 Set 结构转为数组。

    const items = new Set([1, 2, 3, 4, 5]);
    const array = Array.from(items);

    这就提供了去除数组重复成员的另一种方法。

    function dedupe(array) {
      return Array.from(new Set(array));
    }
    
    dedupe([1, 1, 2, 3]) // [1, 2, 
  • 相关阅读:
    ABAP-smartforms
    字符串截取,长度获取
    ',' 导致excel 分列显示
    SALV使用
    SALV双击事件,相应另一个SALV
    CLEAR REFRESH区别
    SY-INDEX和SY-TABIX区别
    JIT机制对运行速度的优化
    《大道至简》读后感
    N皇后问题
  • 原文地址:https://www.cnblogs.com/sangzs/p/8484458.html
Copyright © 2011-2022 走看看