js 数据结构(四):集合

集合

集合是由一组无序且唯一(即不能重复)的项组成。这个数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中。

我们来实现集合, 下面是Set类的骨架:

function Set() {
    var items = {};
    this.add = function (value) {};     // 向集合添加一个新项
    this.remove= function (value) {};   // 从集合移除一个值
    this.has = function (value) {};     // 如果值在集合中,返回true,否则返回false
    this.clear = function () {};        // 移除集合中的所有项
    this.size = function () {};         // 返回集合所包含元素的数量,与数组length属性类似
    this.values = function () {};       // 返回一个包含集合中所有值的数组。
}

has(value) 方法:

this.has = function(value){
    return value in items;
};

除了使用javascript中的in操作符来验证给定的值是否是items对象的属性,我们还可以使用hasOwnProperty,该方法返回一个表面对象是否具有特定属性的布尔值。

this.has = function(value){
    return items.hasOwnProperty(value);
};

add(value) 方法:

this.add = function(value){
    if (!this.has(value)){
        items[value] = value; // 不存在就添加
        return true;
    }
    return false;
};

remove(value) 方法:

this.remove = function(value){
    if (this.has(value)){
        delete items[value];  
        return true;
    }
    return false;
};

 clear() 方法:

this.clear = function(){
    items = {}; // 重新赋值达到清空的目的
};

 size 方法:

this.size = function(){
    return Object.keys(items).length; 
};

还有一种方法:

this.sizeLegacy = function(){
    var count = 0;
    for(var prop in items) { 
        if(items.hasOwnProperty(prop)) {
            ++count; 
        }
    }
    return count;
};

参考链接: 学习JavaScript数据结构与算法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值