xiaolizi007
3/24/2017 - 8:57 AM

js键值对class

js dictiionary #js

/////// map 类

function classMap() {

  this.map = new Array();
  
  var struct = function(key, value){
      this.key = key;
   this.value = value;
 };
 
  this.lookUp = function (key){
   for (var i = 0; i < this.map.length; i++)
   {
  if ( this.map[i].key === key )
  {
    return this.map[i].value;
  }
   }   
   return null;
 };
  
  this.setAt = function (key, value){  
      for (var i = 0; i < this.map.length; i++)
   {
  if ( this.map[i].key === key )
  {
    this.map[i].value = value;
    return;
  }
   }   
   this.map[this.map.length] = new struct(key,value); 
 };
  
  this.removeKey = function removeKey(key){
   var v;
   for (var i = 0; i < this.map.length; i++)
   {
  v = this.map.pop();
  if ( v.key === key )
    continue;
    
  this.map.unshift(v);
   }
 };
  
  this.getCount = function(){
   return this.map.length;
 };
 
  this.isEmpty = function(){
   return this.map.length <= 0;
 };
}
////////////////////////////////////////////////////////////////////////////////////////////////

/********************调用***********************/

window.onload = function(){

  var map = new classMap();
  alert("is the map empty? " + map.isEmpty());
  // string to array
  map.setAt("sw1", "aaaaa");
  map.setAt("sw2", "bbbbb");
  map.setAt("sw3", "ccccc");
  alert(map.lookUp("sw1")); 
  alert(map.lookUp("sw2")); 
  alert(map.lookUp("sw3")); 
  alert(map.getCount());
 
}