用Javascript寫的一個映射表類

來源:互聯網
上載者:User

用Javascript寫的一個映射表類    

該類可以通過關鍵字(key)尋找相對應的值(value),關鍵字的類型可以是String、Number、Boolean類型,值的類型不限,代碼如下:

<script>
function struct(key, value){

  this.key = key;
  this.value = value;

}

function setAt(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);

}

function lookUp(key)
{
  for (var i = 0; i < this.map.length; i++)
  {
    if ( this.map[i].key === key )
    {
      return this.map[i].value;
    }
  }
 
  return null;
}

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);
  }
}

function getCount(){
  return this.map.length;
}

function isEmpty(){
  return this.map.length <= 0;
}

function classMap() {

  this.map = new Array();

  this.lookUp = lookUp;
  this.setAt = setAt;
  this.removeKey = removeKey;
  this.getCount = getCount;
  this.isEmpty = isEmpty;
}

window.onload = function(){

  var map = new classMap();

  alert("is the map empty? " + map.isEmpty());
 
  // string to array
  map.setAt("sw1", new Array("sw1_1"));
  map.setAt("sw2", new Array("sw2_1", "sw2_2"));
  map.setAt("sw3", new Array("sw3_1", "sw3_2", "sw3_3"));
  alert(map.lookUp("sw5")); // null
  alert(map.lookUp("sw2")); // "sw2_1, sw2_2"
 
  alert(map.getCount()); // 3
 
  // number to string
  map.setAt(1, "sw1");
  map.setAt(2, "sw2");
  alert(map.lookUp(2)); // "sw2"
  map.setAt(2, new Array("sw2_1", "sw2_2"));
  alert(map.lookUp(2)); // "sw2_1, sw2_2"
 
  alert(map.getCount()); // 5
 
  // string to number
  map.setAt("1", 1);
  map.setAt("2", 2);
  alert(map.lookUp("1")); // 1
  alert(map.lookUp(1)); // "sw1"
  map.setAt("sw3", 33);
  alert(map.lookUp("sw3")); // 33
 
  alert(map.getCount()); // 7
 
  // number to number
  map.setAt(1, 11);
  map.setAt(2, 22);
  alert(map.lookUp(1)); // 11
 
  alert(map.getCount()); // 7
 
  map.removeKey(1);
  alert(map.lookUp(1)); // null
 
  alert(map.getCount()); // 6
 
  // boolean to array
  map.setAt(false, new Array("false", "true"));
  alert(map.lookUp(false));
 
  alert(map.getCount()); // 7

}
</script> 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.