JavaScript資料結構-字典

來源:互聯網
上載者:User

標籤: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"];  //  [1, undefined, 3]

結果是直接刪除了索引和值一起刪除了


如果向數組中添加一個值?

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資料結構-字典

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.