一、集合
集合特性:
(1)元素無重複性: A = {1,2,3}
(2)空集: A= {}
(3)子集: A = {1,2,3}, B = {1,2},B是A的子集
二、模擬實現ES6中的Set數據結構
實現Set中的方法:
(1)has(value):查詢集合中是否存在某元素
(2)add(value):向集合中添加某元素
(3)remove(value): 移除元素
(4)clear() 清除所有元素
(5)value(): 提取集合所有值合併成數組
(6)getItems():檢查集合
(7)size():集合長度
var Set1 = function() {
var items = {};
// has 判斷集合中是否存在某元素
this.has = function(value) {
return items.hasOwnProperty(value);
}
// add 添加元素
this.add = function(value) {
if(this.has(value)) {
return false;
}
items[value] = value;
return value;
}
// remove 移除元素
this.remove = function(value) {
if(!this.has(value)) {
return false;
}
delete(items[value]);
}
// clear 清除所有元素
this.clear = function() {
items = {};
}
// value 提取集合所有值合併成數組
this.value = function() {
var values = [];
for(var i in items) {
if(items.hasOwnProperty(i)) {
values.push(items[i]);
}
}
return values;
}
// getItems 檢查
this.getItems = function() {
return items;
}
// size ES6寫法
this.size = function() {
return Object.keys(items).length;
}
// size ES5寫法
// this.size = function() {
// var count = 0;
// for(var i in items) {
// if(items.hasOwnProperty(i)) {
// count ++ ;
// }
// }
// return count;
// }
}
var set1 = new Set1();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
console.log(set1.getItems());
console.log(set1.has(3));
set1.remove(2);
console.log(set1.getItems());
console.log(set1.value());
console.log(set1.size());
set1.clear()
console.log(set1.getItems());
並集:獲取兩個集合中的元素,分別變量add進新集合,返回新集合
this.union = function(otherSet) {
var resultSet = new Set1();
// 遍歷本身的項並加入到新集合中
var arr = this.value();
for(var i = 0; i < arr.length; i++) {
resultSet.add(arr[i])
}
// 遍歷另一個集合的項並加入到新集合中
arr = otherSet.value();
for(var i = 0; i < arr.length; i++) {
resultSet.add(arr[i])
}
// 返回新集合
return resultSet;
}
intersection 交集:遍歷第一個集合的元素時查看另一集合是否有該元素,如果有就加入新集合
this.intersection = function(otherSet) {
var resultSet = new Set1();
var arr = this.value();
for(var i = 0; i < arr.length; i++) {
if(otherSet.has(arr[i])) {
resultSet.add(arr[i])
}
}
return resultSet;
}
difference 差集:與交集相反
this.difference = function(otherSet) {
var resultSet = new Set1();
var arr = this.value();
for(var i = 0; i < arr.length; i++) {
if(!otherSet.has(arr[i])) {
resultSet.add(arr[i])
}
}
return resultSet;
}
三、ES6中的Set和WeakSet數據結構
(一)Set
ES6中創建集合時可使用數組:
let set1 = new Set([1,2,3]);
並集:
let a = new Set([1,2,3]);
let b = new Set([2,3,4,5]);
// 並集
let union1 = new Set([...a,...b]); // Set(5) {1, 2, 3, 4, 5}
// 交集
let intersection1 = new Set([...a].filter(x => b.has(x))); // Set(2) {2, 3}
// 差集
let difference1 = new Set([...a].filter(x => !b.has(x))); // Set(1) {1}
console.log(union1);
console.log(intersection1);
console.log(difference1);