Js算法中的字典

2,635 阅读1分钟

字典的常见操作

  • set(key,value):向字典中添加新元素
  • remove(key):通过使用键值来从字典中移除键值对应的数据值。
  • has(key):如果某个键值存在于这个字典中,则返回true,反之则返回false。
  • get(key):通过键值查找特定的数值并返回。
  • clear():将这个字典中的所有元素全部删除。
  • size():返回字典所包含元素的数量。与数组的length属性类似。
  • keys():将字典所包含的所有键名以数组形式返回。
  • values():将字典所包含的所有数值以数组形式返回。

字典的实现

class Ditionary{
    constructor(){
        this.items={}
    }
    //向字典添加新的元素
    set(key,value){
        this.items[key]=value
    }
    //判断字典是否存在key
    has(key){
        return this.items.hasOwnProperty(key)
    }
    //从字典中移除元素
    remove(key){
        //判断字典是否存在
        if(!has(key)) return false
        //从字典删除key
        delete this.items[key]
        return true
    }
    //根据key获取value
    get(key){
        return this.has(key) ? this.items[key]:underfined
    }
    //获取所有的Key
    keys(){
        return Object.keys(this.items)
    }
    //获取所有的value
    values(){
        return Object.values(this.items)
    }
    //size方法
    size(){
        return this.keys().length
    }
    //clear方法
    clear(){
      this.items={}  
    }
}
var dict=new Dictionary()
dict.set("age",18)
dict.set("name","Star")
dict.set("height",1.70)
dict.set("address","广州市")
console.log(dict)
dict.remove("height")
console.log(dict.keys())