欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js数据结构Map -----字典

程序员文章站 2024-02-20 19:18:58
...
// Map
        function Dictionary() {
            var items = {};
            this.has = function (key) {
                return key in items;
            }
            this.set = function (key, value) {
                items[key] = value; //{1}
            }
            this.remove = function (key) {
                if (this.has(key)) {
                    delete items[key];
                    return true
                }
                return false
            }
            this.get = function (key) {
                return this.has(key) ? items[key] : undefined;
            };
            this.values = function () {
                var values = []
                for (var k in items) { //{1}
                    if (this.has(k)) {
                        values.push(items[k]); //{2}
                    }
                }
                return values;
            };
            this.getItems = function () {
                return items;
            }
            this.size = function(){
                return Object.keys(items).length
            }
            this.keys = function(){
                return Object.keys(items)
            }

        }
        var dictionary = new Dictionary();
    dictionary.set('Gandalf', '[email protected]');
    dictionary.set('John', '[email protected]');
    dictionary.set('Tyrion', '[email protected]');
    console.log(dictionary.has('Gandalf'));
    console.log(dictionary.size());
    console.log(dictionary.keys());
    console.log(dictionary.values());
    console.log(dictionary.get('Tyrion'));