are there dictionaries in javascript like python?

前端 未结 7 713
轻奢々
轻奢々 2020-12-07 18:59

i need to make a dictionary in javascript like this

i dont remember the exact notation, but it was something like:

states_dictionary={ CT=[alex,harry         


        
相关标签:
7条回答
  • 2020-12-07 19:11

    This is an old post, but I thought I should provide an illustrated answer anyway.

    Use javascript's object notation. Like so:

    states_dictionary={ 
         "CT":["alex","harry"], 
         "AK":["liza","alex"], 
         "TX":["fred", "harry"]
    };
    

    And to access the values:

    states_dictionary.AK[0] //which is liza
    

    or you can use javascript literal object notation, whereby the keys not require to be in quotes:

    states_dictionary={ 
         CT:["alex","harry"], 
         AK:["liza","alex"], 
         TX:["fred", "harry"]
    };
    
    0 讨论(0)
  • 2020-12-07 19:17

    Use JavaScript objects. You can access their properties like keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org

    0 讨论(0)
  • 2020-12-07 19:21

    An old question but I recently needed to do an AS3>JS port, and for the sake of speed I wrote a simple AS3-style Dictionary object for JS:

    http://jsfiddle.net/MickMalone1983/VEpFf/2/

    If you didn't know, the AS3 dictionary allows you to use any object as the key, as opposed to just strings. They come in very handy once you've found a use for them.

    It's not as fast as a native object would be, but I've not found any significant problems with it in that respect.

    API:

    //Constructor
    var dict = new Dict(overwrite:Boolean);
    
    //If overwrite, allows over-writing of duplicate keys,
    //otherwise, will not add duplicate keys to dictionary.
    
    dict.put(key, value);//Add a pair
    dict.get(key);//Get value from key
    dict.remove(key);//Remove pair by key
    dict.clearAll(value);//Remove all pairs with this value
    dict.iterate(function(key, value){//Send all pairs as arguments to this function:
        console.log(key+' is key for '+value);
    });
    
    
    dict.get(key);//Get value from key
    
    0 讨论(0)
  • 2020-12-07 19:23

    Have created a simple dictionary in JS here:

    function JSdict() {
        this.Keys = [];
        this.Values = [];
    }
    
    // Check if dictionary extensions aren't implemented yet.
    // Returns value of a key
    if (!JSdict.prototype.getVal) {
        JSdict.prototype.getVal = function (key) {
            if (key == null) {
                return "Key cannot be null";
            }
            for (var i = 0; i < this.Keys.length; i++) {
                if (this.Keys[i] == key) {
                    return this.Values[i];
                }
            }
            return "Key not found!";
        }
    }
    
    
    // Check if dictionary extensions aren't implemented yet.
    // Updates value of a key
    if (!JSdict.prototype.update) {
        JSdict.prototype.update = function (key, val) {
            if (key == null || val == null) {
                return "Key or Value cannot be null";
            }
            // Verify dict integrity before each operation
            if (keysLength != valsLength) {
                return "Dictionary inconsistent. Keys length don't match values!";
            }
            var keysLength = this.Keys.length;
            var valsLength = this.Values.length;
            var flag = false;
            for (var i = 0; i < keysLength; i++) {
                if (this.Keys[i] == key) {
                    this.Values[i] = val;
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return "Key does not exist";
            }
        }
    }
    
    
    
    // Check if dictionary extensions aren't implemented yet.
    // Adds a unique key value pair
    if (!JSdict.prototype.add) {
        JSdict.prototype.add = function (key, val) {
            // Allow only strings or numbers as keys
            if (typeof (key) == "number" || typeof (key) == "string") {
                if (key == null || val == null) {
                    return "Key or Value cannot be null";
                }
                if (keysLength != valsLength) {
                    return "Dictionary inconsistent. Keys length don't match values!";
                }
                var keysLength = this.Keys.length;
                var valsLength = this.Values.length;
                for (var i = 0; i < keysLength; i++) {
                    if (this.Keys[i] == key) {
                        return "Duplicate keys not allowed!";
                    }
                }
                this.Keys.push(key);
                this.Values.push(val);
            }
            else {
                return "Only number or string can be key!";
            }
        }
    }
    
    // Check if dictionary extensions aren't implemented yet.
    // Removes a key value pair
    if (!JSdict.prototype.remove) {
        JSdict.prototype.remove = function (key) {
            if (key == null) {
                return "Key cannot be null";
            }
            if (keysLength != valsLength) {
                return "Dictionary inconsistent. Keys length don't match values!";
            }
            var keysLength = this.Keys.length;
            var valsLength = this.Values.length;
            var flag = false;
            for (var i = 0; i < keysLength; i++) {
                if (this.Keys[i] == key) {
                    this.Keys.shift(key);
                    this.Values.shift(this.Values[i]);
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                return "Key does not exist";
            }
        }
    }
    

    The above implementation can now be used to simulate a dictionary as:

    var dict = new JSdict();
    
    dict.add(1, "one")
    
    dict.add(1, "one more")
    "Duplicate keys not allowed!"
    
    dict.getVal(1)
    "one"
    
    dict.update(1, "onne")
    
    dict.getVal(1)
    "onne"
    
    dict.remove(1)
    
    dict.getVal(1)
    "Key not found!"
    

    This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.

    Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.

    Hope this helps!

    EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.

    However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.

    Viz: dict.hasOwnProperty(key) and delete dict[key]

    Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array

    THanks!

    0 讨论(0)
  • 2020-12-07 19:33

    There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in MDN. Example:

    let map = new Map();
    map.set('key', {'value1', 'value2'});
    let values = map.get('key');
    

    Without support for ES6 you can try using objects:

    var x = new Object();
    x["Key"] = "Value";
    

    However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the "object-array" in a for-in-loop.

    0 讨论(0)
  • 2020-12-07 19:36

    I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

    var dict = new Map();
    dict.set("foo", "bar");
    
    //returns "bar"
    dict.get("foo");
    

    Unlike javascript's normal objects, it allows any object as a key:

    var foo = {};
    var bar = {};
    var dict = new Map();
    dict.set(foo, "Foo");
    dict.set(bar, "Bar");
    
    //returns "Bar"
    dict.get(bar);
    
    //returns "Foo"
    dict.get(foo);
    
    //returns undefined, as {} !== foo and {} !== bar
    dict.get({});
    
    0 讨论(0)
提交回复
热议问题