js实现集合方法
来源:互联网 发布:设计模式 php 编辑:程序博客网 时间:2024/06/07 14:06
var items = new Object();
this.has = function (value) {
//两种方式都可以
//return value in items;
return items.hasOwnProperty(value);
};
this.add = function(value){
if(!this.has(value)){
items[value] = value;
return true;
}
return false;
};
this.remove = function(value){
if(this.has(value)){
delete items[value];
return true;
}
return false;
};
this.clear = function(){
items = {};
};
//以下两种都是返回长度
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;
};
//以下两种都是返回对象里面的内容,只是兼容性不一样,第二个兼容性更好一点
this.values = function () {
return Object.keys(items);
};
this.valuesLegacy = function(){
var keys=[];
for(var key in items){
keys.push(key);
}
return keys;
};
//并集
this.union = function(otherSet){
var unionset = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
unionset.add(values[i]);
};
var values = otherSet.values();
for(var i=0;i<values.length;i++){
unionset.add(values[i]);
}
return unionset;
}
//交集
this.intersection = function(otherSet){
var intersection = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
if(otherSet.has(values[i])){
intersection.add(values[i]);
}
}
return intersection;
}
//差集
this.different = function(otherSet){
var different = new Set();
var values = this.values();
for(var i=0;i<values.length;i++){
if(!otherSet.has(values[i])){
different.add(values[i]);
}
}
return different;
}
var set = new Set();
set.add("hello");
set.add("world");
console.log(set.values());
console.log(set.size());
//并集使用例子
var set1 = new Set();
set1.add("aa");
set1.add("bb");
set1.add("cc");
var set2 = new Set();
set2.add("aa");
set2.add("bbb");
set2.add("cc");
var union12 = set1.union(set2);
console.log(union12.values());//可以把重复的给删除
//交集使用例子
var set11 = new Set();
set11.add("aa");
set11.add("bb");
set11.add("cc");
var set22 = new Set();
set22.add("aa");
set22.add("bbb");
set22.add("cc");
var union1122 = set11.intersection(set22);
console.log(union1122.values());
//差集使用例子
var setc = new Set();
setc.add("aa");
setc.add("bb");
setc.add("cc");
var setd = new Set();
setd.add("aa");
setd.add("bbb");
setd.add("cc");
var unioncd = setc.different(setd);//这个注意调用顺序
console.log(unioncd.values());
- js实现集合方法
- js 方法大集合
- JS 字符串方法集合
- JS实现Map集合
- js 实现map集合
- js实现map集合
- js中数组方法集合
- JS截取字符串方法集合
- JS截取字符串方法集合
- JS截取字符串方法集合
- 客户端JS检测方法集合
- js-实现集合的操作
- JS获取网页宽高方法集合
- 常用JS方法集合(原创-持续更新)
- 原生JS常用的方法集合
- js 实现MAP方法
- js 实现 Privileged 方法
- Js 实现 replaceAll 方法
- 冒泡排序
- 计算圆周率
- String类
- Zookeeper系列(一)
- python字符串函数strip()
- js实现集合方法
- 单例的两种类型,以及介绍
- The study of Class and Instance in Python(20170918)
- LeetCode 80. Remove Duplicates from Sorted Array II
- 洛谷 1533 可怜的狗狗
- Elasticsearch5.6.0安装ik分词器
- JQuery学习笔记2
- ipcs ipcrm命令详解
- Linux Redis 安装