標籤:javascript資料結構-字典
字典
JavaScript 的 Object 類就是以字典的形式設計的
Dictionay 類的基礎是 Array 類, 而不是 Object 類
Array數組也可以定義索引為字串如下:
var array = [1,2,3];array["abc"] = "abc";console.log(array["abc"]);// abc
刪除數組方式:
delete array[1]; // [1, undefined, 3] 和 "abc"的索引
索引還在,值為undefined;
那麼刪除"abc"呢?
delete array["abc"];
結果是直接刪除了索引和值一起刪除了
如果向數組中添加一個值?
array[3] =4;array[4] = 5;array.push(6);console.log(array["abc"]);//[1, 2, 3, 4, 5, 6]
通過array["abc"] 向數組中插入資料,不會影響數組中的索引排列順序.
length屬性
console.log(array.length); // 6
為什麼是數組個數是6個而不是7個嗎?
原因:這是因為當鍵的類型為字串時, length 屬性就不管用了
字典定義方法:
add() // 添加dataStore = new Array(); // 字典內部定義了一個數組find(); // 尋找remoe(); // 刪除showAll();// 顯示count(); // 字典個數clear(); // 清空字典
完整字典代碼:
function Dictionary() { this.add = add; this.datastore = new Array(); this.find = find; this.remove = remove; this.showAll = showAll; this.count = count; this.clear = clear; } function add(key, value) { this.datastore[key] = value; } function find(key) { return this.datastore[key]; } function remove(key) { delete this.datastore[key]; } function showAll() { for each(var key in Object.keys(this.datastore)) { print(key + " -> " + this.datastore[key]); } } function count() { var n = 0; for each(var key in Object.keys(this.datastore)) {++n; } return n; } function clear() { for each(var key in Object.keys(this.datastore)) { delete this.datastore[key]; } }
JavaScript資料結構-字典