SOURCE

// 字典与集合类似,都是不容许重复,集合是{值:值}存储,字典是{键:值}存储
// 添加
// 查找
// 删除
// 判断是否存在
// 清空
// 长度
// 所有键
// 所有值
// 所有元素

class Dictionary{
    constructor(){
        this.items = {}
    }
    // 添加
    set(key,value){
        return this.items[key] = value
    }
    // 查找
    get(key){
        return this.items[key]
    }
    // 删除
    delete(key){
        if(!this.items.hasOwnProperty(key)) return false
        delete this.items[key]
        return true
    }
    // 判断是否存在
    has(key){
        return this.items.hasOwnProperty(key)
    }
    // 清空
    clear(){
        this.items = {}
    }
    // 长度
    size(){
        return Object.keys(this.items).length
    }
    // 所有键
    keys(){
        return Object.keys(this.items)
    }
    // 所有值
    values(){
        return Object.values(this.items)
    }
    // 所有元素
    getItems(){
        return this.items
    }
}

// let Dictionary = require('./dictionary');

let dictionary = new Dictionary();
dictionary.set('Gandalf', 'gandalf@email.com');
dictionary.set('John', 'john@email.com');
dictionary.set('Tyrion', 'tyrion@email.com');
console.log(dictionary.has('Gandalf')); // true
console.log(dictionary.size()); // 3
console.log(dictionary.keys()); // [ 'Gandalf', 'John', 'Tyrion' ]
console.log(dictionary.values()); // [ 'gandalf@email.com', 'john@email.com', 'tyrion@email.com' ]
console.log(dictionary.get('Tyrion')); // tyrion@email.com

dictionary.delete('John');
console.log(dictionary.keys()); // [ 'Gandalf', 'Tyrion' ]
console.log(dictionary.values()); // [ 'gandalf@email.com', 'tyrion@email.com' ]
console.log(dictionary.getItems()); // { Gandalf: 'gandalf@email.com', Tyrion: 'tyrion@email.com' }

console 命令行工具 X clear

                    
>
console