本文實例講述了JS集合set類的實現與使用方法。分享給大家供大家參考,具體如下:
js集合set類的實現
/*js集合set類的實現*/function Set() { this.dataStore = []; this.add = add;//新增元素 this.remove = remove;//刪除元素 this.size = size;//集合的元素個數 this.union = union;//求并集 this.contains = contains;//判斷一個集合中是否包含某個元素 this.intersect = intersect;//交集 this.subset = subset;//判斷一個集合是否是另一個的子集 this.difference = difference;//求補集 this.show = show;//將集合元素顯示出來}function add(data) { if (this.dataStore.indexOf(data) < 0) { this.dataStore.push(data); return true; } else { return false; }}function remove(data) { var pos = this.dataStore.indexOf(data); if (pos > -1) { this.dataStore.splice(pos,1); return true; } else { return false; }}function size() { return this.dataStore.length;}function show() { return "[" + this.dataStore + "]";}function contains(data) { if (this.dataStore.indexOf(data) > -1) { return true; } else { return false; }}function union(set) { var tempSet = new Set(); for (var i = 0; i < this.dataStore.length; ++i) { tempSet.add(this.dataStore[i]); } for (var i = 0; i < set.dataStore.length; ++i) { if (!tempSet.contains(set.dataStore[i])) { tempSet.dataStore.push(set.dataStore[i]); } } return tempSet;}function intersect(set) { var tempSet = new Set(); for (var i = 0; i < this.dataStore.length; ++i) { if (set.contains(this.dataStore[i])) { tempSet.add(this.dataStore[i]); } } return tempSet;}function subset(set) { if (this.size() > set.size()) { return false; } else { for(var member in this.dataStore) { if (!set.contains(member)) { return false; } } } return true;}function difference(set) { var tempSet = new Set(); for (var i = 0; i < this.dataStore.length; ++i) { if (!set.contains(this.dataStore[i])) { tempSet.add(this.dataStore[i]); } } return tempSet;}/*測試例子:求補集。屬于集合cis,不屬于集合it*/var cis = new Set();var it = new Set();cis.add("Clayton");cis.add("Jennifer");cis.add("Danny");it.add("Bryan");it.add("Clayton");it.add("Jennifer");var diff = new Set();diff = cis.difference(it);console.log(cis.show() + " difference " + it.show() + " -> " + diff.show());
這里使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.VeVB.COm/code/HtmlJsRun測試上述代碼,可得如下運行結果:
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數據結構與算法技巧總結》、《JavaScript數學運算用法總結》、《JavaScript排序算法總結》、《JavaScript遍歷算法與技巧總結》、《JavaScript查找算法技巧總結》及《JavaScript錯誤與調試技巧總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答