• 用ES5模拟实现ES6中的Map类


    ECMAScript6原生实现了Map类,即我们所说的字典,字典和集合很像,不过集合是以值值得形式存储元素,字典则是以键值的形式存储元素。字典也叫映射。

     1. 创建一个字典

    function Map() {
        var items = {};
    }

    与Set类一样,我们用Object的实例而不是数组存储元素,我们实现以下方法:

    1.set(key,value):向字典中添加新元素。

    2.remove(key):使用键名从字典中移除相应的元素。

    3.has(key):如果某个键值存在于字典中,返回true,否则返回false。

    4.get(key):通过键名找到指定的值并返回。

    5.clear():清空字典。

    6.size():返回字典中元素个数。

    7.values():将字典所有值以数组形式返回。

    8.getItems():返回items变量,代表字典本身。

    1.1 has和set方法

    this.has = function(key){
            return key in items;
        },
    
    this.set = function(key,value){
            items[key] = value;
        }

    has方法判断某个键值是否在字典中,set方法为字典添加新元素或更新已有元素。

    1.2 remove方法

    this.remove = function(key){
            if (this.has(key)) {
                delete items[key];
                return true;
            }
            return false;
        }

    1.3 get和values方法

    this.get = function(key){
            return this.has(key)?items[key]:undefined;
        },
    
    this.values = function(){
            var values = [];
            for(var k in items){
                if (this.hasOwnProperty(k)) {
                    values.push(items[k]);
                }
            }
            return values;
        }

    要注意的是,for...in会遍历出对象原型上的属性,所以要this.hasOwnProperty()方法选出对象自身的属性。

    1.4 clear,size和getItems方法

    this.clear = function(){
            items = {};
        },
    
    this.size = function(){
            return Object.Keys(items).length;
        },
    
    this.getItems = function(){
            return items;
        }

     以下为完整的Map类代码实现:

    function Map() {
        var items = {};
        this.has = function(key){
            return key in items;
        },
        this.set = function(key,value){
            items[key] = value;
        },
        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){
                if (this.hasOwnProperty(k)) {
                    values.push(items[k]);
                }
            }
            return values;
        },
        this.clear = function(){
            items = {};
        },
        this.size = function(){
            return Object.Keys(items).length;
        },
        this.getItems = function(){
            return items;
        }
    }
  • 相关阅读:
    用Canvas绘制一个钟表
    用css3做一个3D立方体
    函数调用的不同方式,以及this的指向
    Javascript 严格模式use strict详解
    前端开发页面的性能优化方案总结
    Promise对象解读
    Vue爬坑之vuex初识
    WEB前端性能优化小结
    navicat 注册码
    docker
  • 原文地址:https://www.cnblogs.com/Cathamerst/p/7222878.html
Copyright © 2020-2023  润新知