最近寫extjs的時候有個應用場景:我需要獲取幾個store中的數據,但是幾個store中有重複數據,於是想到了java中得set有去重複得功能,由於ES6中新加了set,但是版本問題,怕不兼容,所以選擇了自己實現一個Set.
function Set() {
this.elements = new Array();
//獲取Set元素個數
this.size = function() {
return this.elements.length;
}
//判斷Set是否爲空
this.isEmpty = function() {
return (this.elements.length < 1);
}
//清除Set
this.clear = function() {
this.elements = new Array();
}
//增加一個元素,不重複
this.add = function(value) {
//alert(this.containsKey(_key));
if(this.containsValue(value)){
this.remove(value);
}
this.elements.push(value);
}
//移除一個值
this.remove = function(value) {
var bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i] == value) {
this.elements.splice(i, 1);
return true;
}
}
} catch (e) {
bln = false;
}
return bln;
}
//移除一個值,索引
this.kill=function (index){
this.remove(this.get(index));
}
//得到一個值,索引
this.get = function(_index) {
if (_index < 0 || _index >= this.elements.length) {
return null;
}
return this.elements[_index];
}
//查看是否包含一個值
this.containsValue = function(value) {
var bln = false;
try {
for (i = 0; i < this.elements.length; i++) {
if (this.elements[i] == value) {
bln = true;
}
}
} catch (e) {
bln = false;
}
return bln;
}
}
項目中引用,只需new Set()
//test....
var set = new Set();