JS-集合(并,交,差,子)


我们现在来学习js中的并集,交集,差集,子集

//这是并集的运算!

Set.prototype.union = (otherSet) => {

//    this.  集合对象A

    //    otherSet  集合对象B

    //    创建新的集合,这里集合用户保存并集后的总集合

    let unionSet =new Set()

// console.log('在这里了!')

    //    将A中的集合添加在unionSet中

    let values =this.values()//这里的value就是A集合中所有的值

    console.log(this)

console.log(values)

for (let i =0; i < values.length; i++) {

unionSet.add(values[i])

}

//    取出B中的元素。判断是否添加在新集合中

    values = otherSet.values();

    for (let i =0; i < values.length; i++){

unionSet.add(values[i]);

    }

return unionSet;

}

//这是交集的操作!

Set.prototype.intersection = otherSet => {

// this:集合A

    // otherSet:集合B

    //1.创建新的集合

    let intersectionSet =new Set()

//2.从A中取出一个元素,判断是否同时存在于集合B中,是则放入新集合中

    let values =this.values()

for(let i =0 ; i < values.length; i++){

let item = values[i]

if (otherSet.has(item)) {

intersectionSet.add(item)

}

}

return intersectionSet

}

// 差集的运算

    Set.prototype.difference=(otherSet)=>{

//    this:集合A

    //    otherSet:集合B

    //    创建新的集合

        let  difference=new Set()

//    取出A集合一个个元素,判断是否存在于B中

        let values=this.values()

for (let i=0;i

let item=values[i]

if (!otherSet.has()){

difference.add(item)

}

}

return difference

}

//    子集的实现过程

    Set.prototype.subSet= otherSet =>{

let values=this.values()

for (let i=0;i

            let item=values[i]

if (!otherSet.has(item)){

return false

            }

}

return true

    }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容