关键概念
无序
不重复
并集、交集
定义
跟高中的集合概念一模一样
交并补集
代码实现
function cusSet() {this.dataStore = []this.add = addthis.contains = containsthis.delete = delthis.show = showthis.size = sizethis.union = unionthis.intersection = intersectionthis.complementary = complementarythis.hasSubSet = hasSubSet}function add (el) {if (!this.contains(el)) {this.dataStore.push(el)}}function contains (el) {if (this.dataStore.indexOf(el) > -1) {return true}return false}function del (el) {// if (!this.contains(el)) return falsevar pos = this.dataStore.indexOf(el)if (pos > -1) {this.dataStore.splice(pos, 1)return true}return false}function show () {return this.dataStore}function size () {return this.dataStore.length}// 开始实现 交并补function union (set) {// 并集var tempSet = new cusSet()for (var i = 0; i < set.size(); i++) {tempSet.add(set.dataStore[i])}for (var n = 0; n < this.size(); n++) {tempSet.add(this.dataStore[n])}return tempSet}function intersection (set) {// 交集var tempSet = new cusSet()for (i = 0; i < set.size(); i++) {if (this.contains(set.dataStore[i])) {tempSet.add(set.dataStore[i])}}return tempSet}function complementary (set) {// 补集var tempSet = new cusSet()for (i = 0; i < set.size(); i++) {if (!this.contains(set.dataStore[i])) {tempSet.add(set.dataStore[i])}}return tempSet}// 判断子集function hasSubSet(set) {if (set.size() > this.size()) return falsefor (i = 0; i < set.size(); i++) {if (!this.contains(set.dataStore[i])) {return false}}return true}var class1 = new cusSet()class1.add('小明')class1.add('小张')class1.add('小红')class1.add('jacky')var class2 = new cusSet()class2.add('小红')// class2.add('小绿')class2.add('jacky')class2.add('jacky2')class2.add('jacky3')class2.add('jacky4')class2.add('jacky5')class2.add('jacky6')console.log((class1.intersection(class2)).show())console.log((class1.union(class2)).show())console.log((class1.complementary(class2)).show())console.log(class1.hasSubSet(class2))
