您现在的位置:首页 >> 前端 >> 内容

集合的实现“编程开发”

时间:2017/10/8 10:14:00 点击:

  核心提示:集合: 无序不重复/* Set 集合:不重复并且无序*/function Set() { var items = {}; /*集合中添加一个元素*/ this.add = function(value...

集合: 无序不重复

 

/*
	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

 

作者:网络 来源:qq_2105839