频道栏目
首页 > 资讯 > HTML/CSS > 正文

集合的实现“编程开发”

17-10-08        来源:[db:作者]  
收藏   我要投稿

集合: 无序不重复

 

/*
	Set
	集合:不重复并且无序
*/

function Set() {
	var items = {};

	/*集合中添加一个元素*/
	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.has = function (value) {
		return items.hasOwnProperty(value);
		// return value in items;
	}

	/*清空集合*/
	this.clear = function () {
		items = {};
	}

	/*集合的大小*/
	this.size = function () {
		var cnt = 0;
		for(var name in items) {
			if(this.has(name)) {
				cnt++
			}
		}

		return cnt;
	}

	/*返回一个包含集合中所有元素的数组*/
	this.values = function () {
		var arr = [];
		for(var name in items) {
			if(this.has(name)) {
				arr.push(items[name]);
			}
		}

		return arr;
	}

	this.print = function () {
		console.log(this.values());
	}

	/*并集*/
	this.union = function (other_set) {
		var new_set = new Set();
		var values = this.values();
		for(var i=0; i

 

相关TAG标签
上一篇:jquery扩展方法
下一篇:c语言经典题之大数相加
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站