JavaScript hashmap equivalent

前端 未结 17 1377
执笔经年
执笔经年 2020-11-22 13:23

As made clear in update 3 on this answer, this notation:

var hash = {};
hash[X]

does not actually hash the object X; it actually

17条回答
  •  没有蜡笔的小新
    2020-11-22 14:03

    According to ECMAScript 2015 (ES6), standard JavaScript has a Map implementation. More about which could be found here.

    Basic usage:

    var myMap = new Map();
    var keyString = "a string",
        keyObj = {},
        keyFunc = function () {};
    
    // Setting the values
    myMap.set(keyString, "value associated with 'a string'");
    myMap.set(keyObj, "value associated with keyObj");
    myMap.set(keyFunc, "value associated with keyFunc");
    
    myMap.size; // 3
    
    // Getting the values
    myMap.get(keyString);    // "value associated with 'a string'"
    myMap.get(keyObj);       // "value associated with keyObj"
    myMap.get(keyFunc);      // "value associated with keyFunc"
    

提交回复
热议问题