Structure:
functionMap () { This. Keys =NewArray (); This. data =NewArray (); //to add a key-value pair This. Set =function(key, value) {if( This. data[key] = =NULL) {//if the key does not exist, the "key" array adds the key name This. Keys.push (value); } This. data[key] = value;//Assigning a value to a key}; //gets the value corresponding to the key This. get =function(key) {return This. Data[key]; }; //Remove key values (remove key names from key data and corresponding values) This. remove =function(key) { This. Keys.remove (key); This. Data[key] =NULL; }; //determines whether the key value element is empty This. IsEmpty =function() {return This. Keys.length = = 0; }; //get key value element size This. Size =function() {return This. Keys.length; };//traverse the map to execute the handler function. callback functions function (Key,value,index) {.} This. each =function(FN) {if(typeoffn = ' function '){ return; } varLen = This. Keys.length; for(vari=0;i<len;i++){ varK = This. Keys[i]; fn (k, This. Data[k],i); } }; //Gets an array of key values that returns an array of key-value object {Key,value} This. Entrys =function() {varLen = This. Keys.length; varEntrys =NewArray (len); for(vari = 0; i < Len; i++) {Entrys[i]={key: This. Keys[i], Value: This. Data[i]}; }returnEntrys; }; //overriding the ToString method This. toString =function() {vars = "{"; for(vari=0;i< This. keys.length;i++,s+= ', ') {varK = This. Keys[i]; S+ = + + "=" + This. Data[k]; } s+="}"; returns; }; }
Call:
functionTestMap () {varm =NewMap (); M.put ("Key1 "," value1 "); M.put ("Key2 "," value2 "); M.put ("Key3 "," Value3 "); Alert ("Init:" +m); M.put ("Key1 "," Value4 "); Alert ("Set Key1:" +m); M.remove ("Key2"); Alert ("Remove Key2:" +m); vars = ""; M.each (function(key,value,index) {s+ = index+ ":" + key+ "=" +value+ "/n"; }); alert (s); }
Implementation of JS ordered key-value map pair