#Data Structure - Dictionary @(Data Structure & Algorithm)
function Dict(){
this.dataStore = [];
}
Dict.prototype = {
constructor: Dict,
add: function(key,val){
this.dataStore[key] = val;
},
//查找key,返回val
find: function(key){
if (this.dataStore[key] !== undefined){
return this.dataStore[key];
} else {
return false;
}
},
remove: function(key){
if (this.dataStore[key] !== undefined){
delete this.dataStore[key];
return true;
} else {
return false;
}
},
display: function(){
//Object.keys(obj)返回该obj中可被枚举的所有属性
//返回值是一个新数组keys
var keys = Object.keys(this.dataStore);
var key;
for (var i = 0; i< keys.length; i++){
key = keys[i];
console.log(key + ": " + this.dataStore[key]);
}
},
displaySorted: function(){
//keys 为以数字为键的数组,可以使用.sort()
var keys = Object.keys(this.dataStore).sort();
var key;
for (var i = 0; i< keys.length; i++){
key = keys[i];
console.log(key + ": " + this.dataStore[key]);
}
},
count: function(){
var keys = Object.keys(this.dataStore);
return keys.length;
},
clear: function(){
this.dataStore = [];
}
};
var dict = new Dict();
dict.add("a2",1);
dict.add("a1",2);
dict.add("a3",3);
两种遍历方式:
for (key in dataStore)
与dataStore.hasOwnProperty(key)
判断Object.keys(dataStore)
与keys
array loop
推荐方法2,因为keys
array可以使用keys.sort()
来排序,也可以使用keys.length
来求长度