javascript 集合操作

 集合常见方法

//集合封装
function set(){
    this.items={}
}
set.prototype.add=function(val){
    if(this.has(val))return false
    this.items[val]=val
    return true
}
set.prototype.has=function(val){
    return this.items.hasOwnProperty(val)
}
set.prototype.remove=function(val){  
    if(!this.has(val))return false  
    delete this.items[val]   
    return true 
}
set.prototype.clear=function(){
    this.items={}
}
set.prototype.values=function(){ //以数值形式输出
    return Object.keys(this.items)
}
set.prototype.size=function(){
    return Object.keys(this.items).length
}
var l=new set()
console.log(l.add(123)) //true
console.log(l.add(123)) //false
l.add(564)
console.log(l.remove(123)) //true
// console.log(l.has(123))
// console.log(l.has(654))
console.log(l.values()) //["564"]
l.add(23)
l.add(64)
console.log(l.values())//["564","23","64"]
l.clear()
console.log(l.values())//[]
原文地址:https://www.cnblogs.com/finghi/p/15337204.html