iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 22
0
自我挑戰組

透過JavaScript學習演算法與資料結構系列 第 22

字典(Dictionary)

字典是還蠻常見的資料結構,它的{Key:Value}結構讓我們可以很快地對資料做處理。

程式碼如下:

class Dictionary{
  constructor(){
    this.items={}
  }
  has(key){
    return this.items.hasOwnProperty(key);
  }
  set(key,value){
    this.items[key]=value;
  }
  get(key){
    return this.items.hasOwnProperty(key) ? this.items[key]:undefined;
  }
  values(){
    return Object.values(this.items);
  }
  keys(){
    return Object.keys(this.items);
  }
  getItems(){
    return this.items;
  }
  clear(){
    this.items={};
  }
  size(){
    return Object.keys(this.items).length;
  }
  remove(key){
    if(this.items.hasOwnProperty(key)) {
      delete this.items[key];
      return true;
    }
    return false;
  }
}

const dictionary=new Dictionary();
dictionary.set('price',100);
console.log(dictionary.has('price')); 
console.log(dictionary.keys()); 
console.log(dictionary.values());
console.log(dictionary.getItems()); 
console.log(dictionary.get('price')); 
dictionary.remove('price');
console.log(dictionary.keys());
dictionary.set('quantity',5);
console.log(dictionary.getItems()); 
dictionary.clear();
console.log(dictionary.getItems()); 

程式碼


上一篇
堆積(Heap)
下一篇
雜湊表(Hash Table)
系列文
透過JavaScript學習演算法與資料結構30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言