字典,就是以 [键, 值] 的形式来存储元素,也常叫 映射 , Map 。
class ValuePair {constructor(key, value) {this.key = key;this.value = value;}toString() {return `[#${this.key}: ${this.value}]`;}}class Dictionary {constructor() {this.table = {};}toStrFn(item) {if (item === null) {return 'NULL';} else if (item === undefined) {return 'UNDEFINED';} else if (typeof item === 'string' || item instanceof String) {return `${item}`;}return item.toString();}set(key, value) {if (key != null && value != null) {const tableKey = this.toStrFn(key);this.table[tableKey] = new ValuePair(key, value);return true;}return false;}remove(key) {if (this.hasKey(key)) {delete this.table[this.toStrFn(key)];return true;}return false;}hasKey(key) {return this.table[this.toStrFn(key)] ? true : false;}get(key) {const valuePair = this.table[this.toStrFn(key)];return valuePair ? valuePair.value : undefined;}clear() {this.table = {};}size() {return Object.keys(this.table).length;}isEmpty() {return this.size() === 0;}keys() {return this.keyValues().map(item => item.key);}values() {return this.keyValues().map(item => item.value);}keyValues() {return Object.values(this.table);}forEach(callback) {const valuePair = this.keyValues();for (let i = 0; i < valuePair.length; i++) {const result = callback(valuePair[i].key, valuePair[i].value);if (!result) break;}}}const dictionary = new Dictionary();dictionary.set('Gandalf', 'gandalf@email.com');dictionary.set('John', 'johnsnow@email.com');dictionary.set('Tyrion', 'tyrion@email.com');console.log(dictionary.get('John'))
