標籤:blog http io ar java for strong sp 資料
Dictionary類的基礎是數組不是對象;字典的主要用途是通過鍵取值;
基本定義:
function Dictionary() { this.dataStore = new Array(); this.add = add; this.find = find; this.remove = remove; this.showAll = showAll;}function add(key,value) { this.dataStore[key] = value;}function find(key) { return this.dataStore[key];}function remove(key) { delete this.dataStore[key];}function showAll() { var keys = Object.keys(this.dataStore),key; for(var i = 0; i < keys.length; ++i) { key = keys[i]; console.log(key + " -> " + this.dataStore[key]); }}
操作:demo
添加其他功能:
- 統計:
function count() { return Object.keys(this.dataStore).length;}
- 清空:
function clear() { var keys = Object.keys(this.dataStore),key; for(var i = 0; i < keys.length; ++i) { key = keys[i]; delete this.dataStore[key]; }}
- 排序輸出:對showAll進行最佳化
function showSort(check,func) { var keys,key; if(check) { keys = Object.keys(this.dataStore).sort(func); } else { keys = Object.keys(this.dataStore); } for(var i = 0; i < keys.length; ++i) { key = keys[i]; console.log(key + " -> " + this.dataStore[key]); }}
操作:demo;
js:資料結構筆記6--字典