資料結構之字典
阿新 • • 發佈:2018-12-11
JavaScript實現字典
- 字典資料結構
- 建立字典
1. 連結串列資料結構 在電腦科學中,關聯陣列(英語:Associative Array),又稱對映(Map)、字典(Dictionary)是一個抽象的資料結構,它包含著類似於(鍵,值)的有序對。
完整程式碼
const Dictionary = function() { let items = {}, length = 0; this.set = function(key, value) { items[key] = value; length++; } this.delete = function(key) { if (this.has(key)) { delete items[key]; length--; return true; } return false; } this.has = function(key) { return items.hasOwnProperty(key); } this.get = function(key) { // 通過鍵值查詢特定的數值並fa return this.has(key) ? items[key] : undefined; } this.clear = function() { items = {}; } this.size = function() { return length; } this.keys = function() { // 將字典所包含的所有key以陣列的形式返回 let keys = []; for (let k in items) { if (this.has(k)) { keys.push(k); } } return keys; } this.values = function() { // 將字典所包含的所有value以陣列的形式返回 let values = []; for (let k in items) { if (this.has(k)) { values.push(items[k]); } } return values; } this.getItems = function() { return items; } }