JS 求交集,并集,差集,子集 forEach和es6两种方法

1.并集: [A B C R U ]#

```
let set111 = new Set(["A", "B", "C"])
let set222 = new Set(["A", "R", "U"])

let unionset = new Set();

set111.forEach((ele) => {
    if (!unionset.has(ele)) {
        unionset.add(ele)
    }
})

set222.forEach((ele) => {
    if (!unionset.has(ele)) {
        unionset.add(ele)
    }
})

console.log(unionset);

//es6
let union = new Set([...set111, ...set222]);
console.log(union);  
```

2.交集: [A ]#

let differtset = new Set();
set111.forEach((ele) => {
if (set222.has(ele)) {
differtset.add(ele)
}
})

console.log(differtset);

//es6
let intersect = new Set([...set111].filter(x => set222.has(x)));
console.log(intersect);

3.差集#


// let set111 = new Set(["A","B","C"])
// let set222 = new Set(["A","R","U"])

let chaset = new Set();

set111.forEach((ele) => {
    if (!set222.has(ele)) {
        chaset.add(ele)
    }
})

console.log(chaset);

//es6
let difference = new Set([...set111].filter(x => !set222.has(x)));
console.log(difference);

4.子集#

// [a] [a,b] 是
let set1 = new Set([“A”, “b”])
let set2 = new Set([“A”, “R”, “U”])
var str = “”
set1.forEach((ele) => {
if (set2.has(ele)) {
str = “true”
} else {
str = “false”
}
})

    console.log(str);```
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 10:52
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务