美文网首页
ES6之Set对象作用

ES6之Set对象作用

作者: 小龙虾Julian | 来源:发表于2020-05-05 17:19 被阅读0次

    1、数组去重

    var mySet = new Set([1, 2, 3, 4, 4]);
    [...mySet];     // [1, 2, 3, 4]
    

    2、并集

    var a = new Set([1, 2, 3]);
    var b = new Set([4, 3, 2]);
    var union = new Set([...a, ...b]); 
    console.log(union);     // {1, 2, 3, 4}
    

    3、交集

    var a = new Set([1, 2, 3]);
    var b = new Set([4, 3, 2]);
    var intersect = new Set([...a].filter(x => b.has(x))); 
    console.log(intersect)     // {2, 3}
    

    4、差集

    var a = new Set([1, 2, 3]);
    var b = new Set([4, 3, 2]);
    var difference1 = new Set([...a].filter(x => !b.has(x))); 
    console.log(difference1)     // a与b的差集是{1}
    var difference2 = new Set([...b].filter(x => !a.has(x))); 
    console.log(difference2)     // a与b的差集是{4}
    var difference3 =new Set([...[...a].filter(x => !b.has(x)),...[...b].filter(x => !a.has(x))]);     
    console.log(difference3)      // {1,4}
    

    相关文章

      网友评论

          本文标题:ES6之Set对象作用

          本文链接:https://www.haomeiwen.com/subject/ihtvghtx.html