国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JS集合set類的實現(xiàn)與使用方法示例

2019-11-19 12:11:03
字體:
供稿:網(wǎng)友

本文實例講述了JS集合set類的實現(xiàn)與使用方法。分享給大家供大家參考,具體如下:

js集合set類的實現(xiàn)

/*js集合set類的實現(xiàn)*/function Set() {  this.dataStore = [];  this.add = add;//新增元素  this.remove = remove;//刪除元素  this.size = size;//集合的元素個數(shù)  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測試上述代碼,可得如下運行結(jié)果:

更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)學運算用法總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯誤與調(diào)試技巧總結(jié)

希望本文所述對大家JavaScript程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 宜城市| 麻江县| 福建省| 蓬安县| 康乐县| 娱乐| 唐河县| 开原市| 榕江县| 平顶山市| 丰城市| 日土县| 潞城市| 清河县| 巴彦县| 涞水县| 普陀区| 监利县| 镇沅| 金堂县| 保靖县| 开平市| 建宁县| 北宁市| 紫阳县| 芜湖县| 旬邑县| 会理县| 萝北县| 菏泽市| 广河县| 前郭尔| 襄汾县| 嵊泗县| 宜昌市| 曲阳县| 宾川县| 南江县| 闸北区| 科尔| 利川市|