集合
集合封装
其实菜鸟刚看到这个,以为是自己面试题里面的求子集问题,结果发现好像并不是!
集合方法
方法实现
这里实现集合的方式是Object,感觉视频讲得有点太简单,让菜鸟感觉有点不知道原因的感觉,可能是本来就很简单!
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>集合</title>
</head>
<body>
<script>
function Set(){
// 属性
this.items = {};
// 方法
// add方法
Set.prototype.add = function(value){
// 判断当前集合是否含有该元素
if(this.has(value)){
return false;
}
// 将元素添加进集合 --> value同时作为key和value
this.items[value] = value;
return true;
}
// remove方法
Set.prototype.remove = function(value){
// 判断当前集合是否含有该元素
if(!this.has(value)){
return false;
}
// 删除对象key的办法
delete this.items[value];
return true;
}
// has方法
Set.prototype.has = function(value){
// key和value一样 --> hasOwnProperty检测一个属性是否是对象的 **自有属性**
return this.items.hasOwnProperty(value);
}
// clear方法
Set.prototype.clear = function(){
this.items = {};
}
// size方法
Set.prototype.size = function(){
// Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和正常循环遍历该对象时返回的顺序一致性
return Object.keys(this.items).length;
}
// values方法
Set.prototype.values = function(){
return Object.keys(this.items);
}
}
</script>
</body>
</html>
菜鸟感觉加上注释之后,似乎好了很多!
注意:
菜鸟发现,这里的values方法返回的结果alert出来顺序不太对!
应该是经过了某种排序!默认就是这种排序,就算你正常遍历也是这种顺序!
MDN官网也是这样的:
感谢:Object.keys(…)对象属性的顺序?
集合间操作
并集
代码
// 并集
Set.prototype.union = function(otherSet){
//this:集合对象A otherSet:集合对象B
// 1.创建一个新的集合
let unionset = new Set();
// 2.将A集合中所有元素添加到新集合中
let values = this.values();
for(let i = 0;i < values.length;i++){
unionset.add(values[i]);
}
// 3 取出B集合中的元素-->添加到新集合(add方法已经做了去重判断)
values = otherSet.values();
for(let i = 0;i < values.length;i++){
unionset.add(values[i]);
}
return unionset;
}
交集
代码
// 交集
Set.prototype.intersection = function(otherSet){
let intersectionSet = new Set();
// 判断this中的值,otherSet里面是否有,有就加入进新的Set
let values = this.values();
for(let i = 0; i < values.length;i++){
let item = values[i];
if(otherSet.has(item)){
intersectionSet.add(item);
}
}
return intersectionSet;
}
差集
代码
// 差集
Set.prototype.difference = function(otherSet){
let differenceSet = new Set();
let values = this.values();
// 判断this中的值是否不在othersSet里面,不在就加入新集合
for(let i = 0;i < values.length;i++){
let item = values[i];
if(!otherSet.has(item)){
differenceSet.add(item);
}
}
return differenceSet;
}
子集
这个思路虽然还要分情况,但是真的写起代码,确实还是只需要循环加判断就行了!因为如果长度大于otherSet,那么肯定也是有元素不在otherSet里面!
// 子集
Set.prototype.subset = function(otherSet){
// 1.遍历this中的元素,如果this中有otherSet中不存在的,返回false
let values = this.values();
for(let i = 0;i < values.length;i++){
let item = values[i];
if(!otherSet.has(item)){
return false;
}
}
return true;
}
字典
这里视频没有写代码啥的,原因是如果用对象封装的话就很像集合,最常用的还是用哈希表封装,但是没学哈希表,现在先了解,后面学了哈希表再来实现!
更多请直接看codewhy老师的简书:https://www.jianshu.com/p/c53460c9c8e4