集合
集合是由一组无序且唯一(即不能重复)的项组成。这个数据结构使用了与有限集合相同的数学概念,但应用在计算机科学的数据结构中。
我们来实现集合, 下面是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数据结构与算法