字典
字典数据结构
- 在字典(或映射)中,我们用[键,值]对的形式来存储数据,其中键用来查询特定的元素
- 在字典中的每个键只能有一个值
帮助方法或类
- 判断元素是否存在
const isExist = (element) => { return element !== undefined && element !== null; };
- 字符串转换函数
/*将传入的参数转换为字符串*/ const toStr = (param) => { if (param === null) { return 'NULL'; } else if (param === undefined) { return 'UNDEFINED'; } else if (typeof param === 'number' || param instanceof Number) { return `${ param}`; } else if (typeof param === 'string' || param instanceof String) { return `${ param}`; } else if (typeof param === 'symbol') { return param; } else { return JSON.stringify(param); } };
- 创建存储键值对对象的类
/*创建存储键值对对象的类*/ class KeyValuePair { constructor(key, value) { this.key = key; this.value = value; } toString() { return `[${ this.key}:${ this.value}]`; } }
创建字典数据结构
- 字典的方法
- set(key,value):向字典中添加新元素,如果key已经存在那么新的值会覆盖旧的值
- hasKey(key):判断某个key是否存在于字典中,存在返回true,否则返回false
- get(key):通过特定的key查找值并返回
- clear():删除字典中的所有的值
- size():返回字典中所包含值的数量。与数组的length属性类似
- isEmpty():判断字典中是否有值,有返回true,否则返回false
- keys():将字典中所有的键以数组的形式返回
- values():将字典中所有的值以数组的形式返回
- keyValues():将字典中所有的[键,值]以数组的形式返回
- forEach(callback):将函数callback用于字典中的每个键值对。callback有两个参数:key和value
- toString()
- 代码
/*创建字典的类*/ class Dictionary { constructor() { this.table = { }; //存储字典中元素的table对象 } // set(key,value):向字典中添加新元素,如果key已经存在那么新的值会覆盖旧的值 set(key, value) { if (isExist(key) && isExist(value)) { const name = toStr(key); this.table[name] = new KeyValuePair(key, value); return true; } return false; } // hasKey(key):判断某个key是否存在于字典中,存在返回true,否则返回false hasKey(key) { const name = toStr(key);