Creating a .net like dictionary object in Javascript

后端 未结 3 1268
甜味超标
甜味超标 2021-01-17 09:04

I want to create a object in JavaScript which will store values in key, value pair and I should be able to pass some key and should be able to get its value back. In .NET wo

3条回答
  •  耶瑟儿~
    2021-01-17 09:33

    Just use a standard javascript object:

    var dictionary = {};//create new object
    dictionary["key1"] = value1;//set key1
    var key1 = dictionary["key1"];//get key1
    

    NOTE: You can also get/set any "keys" you create using dot notation (i.e. dictionary.key1)


    You could take that further if you wanted specific functions for it...

    function Dictionary(){
       var dictionary = {};
    
       this.setData = function(key, val) { dictionary[key] = val; }
       this.getData = function(key) { return dictionary[key]; }
    }
    
    var dictionary = new Dictionary();
    dictionary.setData("key1", "value1");
    var key1 = dictionary.getData("key1");
    

提交回复
热议问题