【前端數據結構基礎】字典

前言

字典是一種以鍵-值對形式存儲數據的數據結構,如同手機通信錄中,想要尋找一個電話時,只要找到名字就能夠找到其電話號碼。
JavaScript的Object類就是以字典的形式設計的。這裏將使用Object類的特性,實現一個Dictionary類,讓字典類型的對象使用起來更加簡單。算法

1、構造字典數據結構

咱們將使用JavaScript實現字典結構,各部分功能使用註釋說明。數組

/**
 * Dictionary 構造方法
 * datastore 存儲數據
 */
function Dictionary () {
  this.datastore = new Array()
  this.add = add
  this.find = find
  this.remove = remove
  this.showAll = showAll
  this.count = count
  this.clear = clear
  this.showAllBySort = showAllBySort
}

/**
 * add() 方法進行添加數據
 * @param {*} key
 * @param {*} value
 */
function add (key, value) {
  this.datastore[key] = value
}

/**
 * find() 方法進行查找key值對應的value
 * @param {*} key
 */
function find (key) {
  return this.datastore[key]
}

/**
 * remove() 方法進行刪除對應的key值鍵值對
 * @param {*} key
 */
function remove(key) {
  delete this.datastore[key]
}

/**
 * showAll() 方法進行遍歷顯示全部的key、value
 */
function showAll () {
  let datakeys = Array.prototype.slice.call(Object.keys(this.datastore))
  for (let key in datakeys) {
    console.log(datakeys[key] + ' -> ' + this.datastore[datakeys[key]])
  }
}

/**
 * showAllBySort() 方法進行遍歷顯示全部排序後的key、value
 */
function showAllBySort () {
  let datakeys = Array.prototype.slice.call(Object.keys(this.datastore)).sort()
  for (let key in datakeys) {
    console.log(datakeys[key] + ' -> ' + this.datastore[datakeys[key]])
  }
}

其中有幾點我的認爲須要強調:數據結構

  1. 咱們想要刪除鍵-值對時須要使用JavaScript中的內置函數——delete。該函數使用對鍵的引用做爲參數,同時刪除鍵與其關聯的值。
  2. 咱們使用Object類keys()方法能夠返回傳入參數中存儲的全部鍵。(Object.keys()for...in循環的區別主要在於for...in循環會枚舉其原型鏈上的屬性)
  3. slice()方法是從已有的數組中返回選定的元素
  4. 當咱們在計算字典中元素的個數時,並無直接使用length方法,由於當鍵的類型爲字符串時,length屬性沒法使用

結束語

使用JavaScript實現字典數據結構相對來講難度不大,但咱們須要注意其中的一些細節部分。函數

參考資料:數據結構與算法JavaScript描述 第7章 字典 因爲書上的源代碼出現了錯誤,所以代碼根據實際運行結果作了相應修改。
相關文章
相關標籤/搜索