function Set() { var items = {}; 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 // es5 以上版本 } this.sizeLegacy = function () { var count = 0; for (var prop in items) { //{5} if (items.hasOwnProperty(prop)) //{6} ++count; //{7} } return count; }; this.values = function () { return Object.keys(items); }; this.valuesLegacy = function () { var keys = []; for (var key in items) { //{7} keys.push(key); //{8} } 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]) } values = otherSet.values() for (var j = 0; j < values.length; j++) { unionSet.add(values[j]) } return unionSet } // 交集 this.intersection = function (otherSet) { var intersectionSet = new Set(); //{1} var values = this.values(); for (var i = 0; i < values.length; i++) { //{2} if (otherSet.has(values[i])) { //{3} intersectionSet.add(values[i]); //{4} } } return intersectionSet; } // 差集 this.difference = function (otherSet) { var differenceSet = new Set(); //{1} var values = this.values(); for (var i = 0; i < values.length; i++) { //{2} if (!otherSet.has(values[i])) { differenceSet.add(values[i]); //{4} } } return differenceSet; //{3} } // 子集 this.subset = function (otherSet) { if (this.size() > otherSet.size()) { //{1} return false; } else { var values = this.values(); for (var i = 0; i < values.length; i++) { //{2} if (!otherSet.has(values[i])) { //{3} return false; //{4} } } return true; //{5} } } } // var set = new Set(); // set.add(1); console.log(set.values()); //输出["1"] // console.log(set.has(1)); //输出true // console.log(set.size()); //输出1 // set.add(2); // console.log(set.values()); //输出["1", "2"] // console.log(set.has(2)); //true // console.log(set.size()); //2 // 并集 var setA = new Set(); setA.add(1); setA.add(2); setA.add(3); var setB = new Set(); setB.add(3); setB.add(4); setB.add(5) setB.add(6) var unionAB = setA.union(setB) console.log(unionAB.values()) // 交集 var intersectionAB = setA.intersection(setB); console.log(intersectionAB.values()); //差集 var differenceAB = setA.difference(setB); console.log(differenceAB.values());