字典和散列表


本节的数据结构中涉及到的代码在gitHub库中()

字典

字典和集合的结构相似,集合是以[值,值]的形式存储元素的,字典则是通过[键,值]的方式来存储元素,字典也称为映射、符号表或者关联数组

接下来会从以下几个地方介绍一下字典,在ECMA2015中包含了一个Map类,它和我们说的字典结构很像,但是不同于存储[值,值]对的形式。

import {defaultToString} from '../utils/index' // 引入公共函数封装的转化字符串的方法
class Dictionary {
    constructor(toStringFn = defaultToString){
        this.toString = toStringFn
        this.table = {} //用来接收存储的[键,值]对
    }
}

接下来我们对Dictionary类进行扩展以下方法

  • set(key,value) : 通过设置键值对向字典中增加新的元素,如果字典中已存在key,则已存在的value值会被新的value替换。
  • remove(key) : 从字典中移除键值对对应的数据值
  • hasKey(key) : 判断字典中是否含有某个键值
  • get(key) : 获取字典中某一键值下的数据值
  • clear() : 清空字典
  • size() : 获取字典中键值对的个数
  • isEmpty() : 判断字典是否为空
  • keys() : 获取字典中所有的键组成的数组
  • values() : 获取字典中所有的值组成的数组
  • keyValues() : 将字典中所有的键值对返回
  • forEach(callbackFn) : 迭代字典中所有的键值对,callbackFn有两个参数,keyvalue 该方法可在回调函数中返回false时停止

下面的代码中,我们依次讲了字典的基本方法,具体应用时,可以在

示例代码如下:

import { defaultToString } from '../utils/index.js'

class Dictionary {
    constructor( toStringFn = defaultToString){
        this.toString = toStringFn
        this.table = {}
    }
    set(key,value){ 
        if (key && value ) {
            this.table[key] = value
            return true
        }
        return false
    }
    remove(key){
        if (key && this.hasKey(key)) {
            delete this.table[key]
            return true
        }
        return false
        
    }
    hasKey(key){
        return Object.prototype.hasOwnProperty.call(this.table,key)
    }
    get(key){
        if (this.hasKey(key)) {
            return this.table[key]
        }
        return undefined
    
    }
    clear(){
        this.table = {}
    }
    size(){
        return Object.keys(this.table).length
    }
    isEmpty(){
        if (this.size() === 0) {
            return true
        }
        return false
    }
    keys(){
      return Object.keys(this.table)  
    }
    values(){
        return Object.values(this.table)
    }
    keyValues(){
        return this.table
    }
}

var dictory = new Dictionary()
dictory.set('name','Alice')
dictory.set('age',30)
dictory.set('country','China')
dictory.set('name','Alice')
console.log(dictory,'dictory') 
/**
 * Dictionary {
  toString: [Function: defaultToString],
  table: { name: 'Alice', age: 30, country: 'China' }
}
 *  */ 
console.log(dictory.hasKey('age')) // true

console.log(dictory.get('name')) // Alice

console.log(dictory.remove('country')) // true
console.log(dictory,'dictory') 
/** 
 * Dictionary {
  toString: [Function: defaultToString],
  table: { name: 'Alice', age: 30 }
} 
*/

console.log(dictory.keys()) // [ 'name', 'age' ]
console.log(dictory.size()) // 2
console.log(dictory.isEmpty()) // false
console.log(dictory.values()) //[ 'Alice', 30 ]
console.log(dictory.keyValues()) // { name: 'Alice', age: 30 }

散列表

散列表又称为hashMap,是Dictionary类中的一种散列表实现方式,散列算法的作用是尽可能快的在数据结构中找都一个值。散列表的作用是给它一个键值,然后返回在表中的地址

还是从创建散列表开始讲起

未完待续…


文章作者: dreamITGirl
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 dreamITGirl !
  目录