-
集合常見的實作方式是哈希表
-
集合通常是一組無序的,不能重復的元素
-
集合的特殊之處在于里面的元素沒有順序,不能重復;即不能通過下標值來訪問,相同的物件在集合中只會存在一份
-
ES6已經有Set類
-
集合類的方法
- add(value):向集合添加一個新的項
- remove(value):從集合移除一個值
- has(value):如果值在集合中,回傳true,否則回傳false
- clear():移除集合中的所有項
- size():回傳集合所包含元素的數量,與陣列的length屬性類似
- values ():回傳一個包含集合中所有值的陣列
-
封裝集合類
function Set(){
//集合屬性
this.items = {}
//集合方法
//1.add()
Set.prototype.add = function(value){
//判斷當前集合中是否已經包含該元素
if(this.has(value)) return false;
this.items[value] = value;
return true;
}
//2.has()
Set.prototype.has = function(value){
return this.items.hasOwnProperty(value);
}
//3.remove()
Set.prototype.remove = function(value){
//判斷當前集合中是否已經包含該元素
if(!this.has(value)) return false;
delete this.items[value];
return true;
}
//4.clear()
Set.prototype.clear = function(v){
this.items = {};
}
//5.size()
Set.prototype.clear = function(v){
return Object.keys(this.items).length;
}
//6.value()
Set.prototype.values = function(v){
return Object.keys(this.items);
}
//集合間的操作
//1.并集
Set.prototype.union = function(otherSet){
var unionSet = new Set();
var values = this.values();
//取出A集合的元素
for(var i=0;i<values.length;i++){
unionSet.add(values[i]);
}
//取出B集合的元素
values = otherSet.values();
for(var i=0;i<values.length;i++){
unionSet.add(values[i]);
}
return unionSet;
}
//2.交集
Set.prototype.intersection = function(otherSet){
var intersectionSet = new Set();
//判斷元素是否同時存在于A和B中
var values = this.values();
for(var i = 0;i<values.length;i++){
var item = values[i];
if(otehrSet.has(item)){
intersectionSet.add(item);
}
}
return intersectionSet;
}
//3.差集
Set.prototype.difference = function(otherSet){
var differenceSet = new Set();
var values = this.values();
for(var i =0;i<values.length;i++){
var item = values[i];
if(!otherSet.has(item)){
differenceSet.add(item)
}
}
return differenceSet;
}
//3.子集
Set.prototype.subSet = function(otherSet){
var values = this.values();
for(var i =0 ;i<values.length;i++){
var item = values[i];
if(!otherSet.has(item)){
return false;
}
}
return true;
}```
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/249493.html
標籤:其他
上一篇:vue+elementUI上傳單張、多張圖片/視頻至oss
下一篇:HTML基礎知識
