當前位置:
首頁 >
Set 的合集 并集 差集
發布時間:2025/4/14
25
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Set 的合集 并集 差集
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
合集
var arr1 = [1,2,3,3,5,4,7]; var arr2 = [2,3,6]; function union() {//先將數組去重let s1 = new Set(arr1);let s2 = new Set(arr2);//[...s1,...s2] 先將兩個數組合并為一個數組 // 去重 new Set([...s1,...s2])// 將集合變成數組 [...array]let allUnion = [...new Set([...s1,...s2])];console.log(allUnion); } union();先聲明兩個數組?
var arr1 = [1,2,3,3,5,4,7]; var arr2 = [2,3,6];創建一個函數 調用這個函數
function union() {} union();合集首先里面的數組是沒有 重復的 我們先將 各自的數組去重?
let s1 = new Set(arr1);let s2 = new Set(arr2);將去重后的數組合并
[...s1,...s2]這個時候我們得到的數組里面 可能有重復的
比如 arr1? 去重后得到 [1,2,3,4,5,7], arr2 去重后 的數組為 [2,3,6]
合并數組得到 [1,2,3,4,5,7,2,3,6]? 數組里面有重復的 所以我們將 這個數組再次去重?
let allUnion = [...new Set([...s1,...s2])]; 將集合變成數組的操作是? ? ? ?[...array] 輸出 結果: [ 1, 2, 3, 5, 4, 7, 6 ] 并集 function Bing () {let s1 = new Set(arr1);let s2 = new Set(arr2);let s3 = [...s1].filter(item=>{return s2.has(item)});console.log(s3); } Bing ();使用 filter 函數進行過濾 符合或者不符合 的情況?
has 函數可以用來 判斷集合是否有某個 數值?
?
輸出 :
[ 2, 3 ] 差集? function Chai() {let s1 = new Set(arr1);let s2 = new Set(arr2);let s3 = [...s1].filter(item=>{return !s2.has(item)});console.log(s3); } Chai();輸出 :
[ 1, 5, 4, 7 ]?
轉載于:https://www.cnblogs.com/guangzhou11/p/11327085.html
總結
以上是生活随笔為你收集整理的Set 的合集 并集 差集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 块级作用域
- 下一篇: Xorequ(BZOJ3329+数位DP