集合的实现3--ES6的set类型
2017-10-05 14:55
435 查看
ES6也实现了Set类型。
ES6入门之set和map
我们看到
我们也可以稍微修改一下程序。使之可以接受参数。
看下面的注释部分。由于使用的是函数表达式(对应的是函数声明)。因此代码得放在合理的位置
ES6入门之set和map
我们看到
var set = new Set([1, 2, 2, 3, 3]); console.log(set);
我们也可以稍微修改一下程序。使之可以接受参数。
看下面的注释部分。由于使用的是函数表达式(对应的是函数声明)。因此代码得放在合理的位置
/* 使用数组来模拟集合 */ function Set(arr) { var items = []; this.add = function (value) { if(this.has(value)) { return false; } items.push(value); return true; } this.has = function (value) { if(items.indexOf(value) == -1) { return false; } return true; } /*添加一些Set初始化的代码*/ if(arr) { for(var i=0; i<arr.length; ++i) { this.add(arr[i]) } } this.remove = function (value) { if(this.has(value)) { var index = items.indexOf(value); items.splice(index, 1); return true; } return false; } this.clear = function () { items = []; } this.size = function () { return items.length; } this.values = function () { return items; } this.print = function () { console.log(items); } this.union = function (other_set) { var new_set = new Set(); var values = this.values(); for(var i=0; i<values.length; ++i) { new_set.add(values[i]); } values = other_set.values(); for(var i=0; i<values.length; ++i) { if(!new_set.has(values[i])) { new_set.add(values[i]); } } return new_set; } this.intersection = function (other_set) { var new_set = new Set(); var values = this.values(); for(var i=0; i<values.length; ++i) { if(other_set.has(values[i])) { new_set.add(values[i]); } } return new_set; } this.difference = function (other_set) { var new_set = new Set(); var values = this.values(); for(var i=0; i<values.length; ++i) { if(!other_set.has(values[i])) { new_set.add(values[i]); } } return new_set; } this.isSubset = function (other_set) { var flag = true; var values = other_set.values(); for(var i=0; i<values.length; ++i) { if(!this.has(values[i])) { return false; } } return true; } } var set = new Set([1, 2, 2, 1, 3]); set.print();
相关文章推荐
- Java 7之集合类型第6篇 - Set集合的实现
- Java 7之集合类型第6篇 - Set集合的实现
- Hibernate--Enum类型的set集合映射到数据库(xml配置文件实现方式)
- Redis源码剖析和注释(十二)--- 集合类型键实现(t_set)
- Redis数据类型与指令详解之集合(t_set)
- Java集合架构--Set接口的几个具体实现类
- 利用Set实现集合元素去重
- Hibernate 多表关联映射- Hibernate中使用的集合类型(set,list,array,bag,map)
- Redis教程(五) 集合(SET)类型
- Set集合及其实现类
- iOS 集合类型 NSSet和NSMutableSet
- Python集合(set)类型的操作
- springmvc 接受数组,集合(list,set)类型的参数
- 第二十节,基本数据类型,集合set、综合应用新数据更新老数据
- Python set集合类型操作总结
- TreeSet集合为什么要实现Comparable?
- Python学习笔记之集合类型(set, frozeset)
- hibernate中一对多映射(set集合中存放的原生数据类型,而不是实体)
- Python 集合(set)类型的操作
- java集合框架之Set集合实现类性能对比