js-実現辞書(キーの記憶)


辞書では、「キー、値」という形でデータを保存します.
jsコードは以下の通りです
function Dictionary(){//   
	var items={};//     Object    
	
	this.has=function(key){//    key   items       
		return key in items;
	};
	this.set=function(key,value){//    
		items[key]=value;
	};
	this.remove=function(key){//  key  
		if(this.has(key)){
			delete items[key];
			return true;
		}
		return false;
	};
	this.get=function(key){//      
		return this.has(key) ? items[key]:undefined;
	};
	this.values=function(){//    value    
		var values=new Array();//       
		for(var k in items){
			if(this.has(k)){
				values.push(items[k]);
			}
		}
		return values;
	};
	this.getItems=function(){//  
		return items;
	};
	this.clear = function () {//  
		items = {};
	};
	this.size = function () {//       
		return Object.keys(items).length;
	};
}
var dictionary= new Dictionary();//new    
//    
dictionary.set('gandalf','[email protected]');
dictionary.set('john','[email protected]');
dictionary.set('tyrion','[email protected]');
//  
console.log(dictionary.size());
console.log(dictionary.values());
console.log(dictionary.get('tyrion'));

/*    :
* 	3
*	[ '[email protected]', '[email protected]', '[email protected]' ]
*	[email protected]
*/