How to create a hash or dictionary object in JavaScript

This question already has an answer here:

  • JavaScript Hashmap Equivalent 17 answers

  • Don't use an array if you want named keys, use a plain object.

    var a = {};
    a["key1"] = "value1";
    a["key2"] = "value2";
    

    Then:

    if ("key1" in a) {
       // something
    } else {
       // something else 
    }
    

    A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.

    Maps do not support the [subscript] notation used by Objects. That syntax implicitly casts the subscript value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key) , .set(key, value) and .has(key) .

    var m = new Map();
    var key1 = 'key1';
    var key2 = {};
    var key3 = {};
    
    m.set(key1, 'value1');
    m.set(key2, 'value2');
    
    console.assert(m.has(key2), "m should contain key2.");
    console.assert(!m.has(key3), "m should not contain key3.");

    You want to create an Object, not an Array.

    Like so,

    var Map = {};
    
    Map['key1'] = 'value1';
    Map['key2'] = 'value2';
    

    You can check if the key exists in multiple ways:

    Map.hasOwnProperty(key);
    Map[key] != undefined // For illustration // Edit, remove null check
    if (key in Map) ...
    
    链接地址: http://www.djcxy.com/p/26640.html

    上一篇: 如何检查数组元素是否存在或不在JavaScript中?

    下一篇: 如何在JavaScript中创建哈希或字典对象