1.概念

  字典采用键值对的方式来实现,可以非常方便的通过键(key)来搜索对应的值(value)。

2.封装字典

// 创建字典的构造函数
function Dictionay() {
  // 字典属性
  this.items = {}

  // 在字典中添加键值对
  Dictionay.prototype.set = function (key, value) {
    this.items[key] = value
  }

  // 判断字典中是否有某个key
  Dictionay.prototype.has = function (key) {
    return this.items.hasOwnProperty(key)
  }

  // 从字典中移除元素
  Dictionay.prototype.remove = function (key) {
    // 1.判断字典中是否有这个key
    if (!this.has(key)) return false
    // 2.从字典中删除key
    delete this.items[key]
    return true
  }

  // 根据key去获取value
  Dictionay.prototype.get = function (key) {
    return this.has(key) ? this.items[key] : undefined
  }

  // 获取所有的keys
  Dictionay.prototype.keys = function () {
    return Object.keys(this.items)
  }

  // 获取所有的value
  Dictionay.prototype.values = function () {
    return Object.values(this.items)
  }

  // size方法
  Dictionay.prototype.size = function () {
    return this.keys().length
  }

  // clear方法
  Dictionay.prototype.clear = function () {
    this.items = {}
  }
}
//测试
var dict = new Dictionay()
dict.set("age", 18)
dict.set("name", "Coderwhy")
dict.set("height", 1.88)
dict.set("address", "广州市")
console.log(dict.keys())      // age,name,height,address
console.log(dict.values())    // 18,Coderwhy,1.88,广州市
console.log(dict.size())      // 4
console.log(dict.get("name")) // Coderwhy
dict.remove("height")
console.log(dict.keys())      // age,name,address
dict.clear()
posted on 2021-03-14 18:35  李起桉  阅读(69)  评论(0编辑  收藏  举报