内容大纲

字典

huan_kong

70字小于1分钟

2023-12-05

介绍

字典就是类似对象的结构:

  • 是通过 key 来取出 value
  • 不可以存在重复的 key
  • 可以通过下标来取出 value

TS实现

namespace 字典 {
  class Map {
    #values: { [key: string]: any } = {}

    has(key: string) {
      return this.#values.hasOwnProperty(key)
    }

    set(key: string, value: any) {
      this.#values[key] = value
    }

    remove(key: string) {
      if (!this.has(key)) return false
      delete this.#values[key]
    }

    get(key: string) {
      return this.has(key) ? this.#values[key] : undefined
    }

    keys() {
      return Object.keys(this.#values)
    }

    values() {
      return Object.values(this.#values)
    }

    size() {
      return this.keys().length
    }

    clear() {
      this.#values = {}
    }
  }
}