版权声明:三和小钢炮 https://blog.csdn.net/fwx426328/article/details/82316288
javaScript数据结构之集合
01 集合
集合是由一组无序且唯一的项组成。
02 创建一个集合
在es6中已经有Set,大概用法如下:
var set = new Set([1,2,3,1]);
set.add(5);
console.log(set);
我们写一个Set
function Set(arr) {
var _item = {};
(function Set(list){
if(list) {
for(var i = 0; i < list.length; i++) {
_item[list[i]] = list[i];
}
}
})(arr);
this.has = function(value) {
return value in _item;
};
this.add = function(value) {
var isSucc = false;
if (!this.has(value)) {
_item[value] = value;
isSucc = true;
}
return isSucc;
};
this.remove = function(value) {
var isSucc = false;
if(!this.has(value)) {
delete _item[value];
isSucc = true;
};
return true;
};
this.clear = function() {
_item = {};
};
this.size = function() {
var count = 0;
for(var attr in _item) {
if(_item.hasOwnProperty(attr)) {
++count;
};
}
return count;
//return Object.keys(_item).length;
};
this.values = function() {
var keys = [];
for(var attr in _item) {
if(_item.hasOwnProperty(attr)) {
keys.push(attr);
};
}
return keys;
//return Object.keys(_item);
};
this.forEach = function(fn) {
this.values().forEach(fn);
}
}
var s = new Set([1,23,4,4,1]);
s.add(5);
console.log(s);