第七章(字典)

字典是“键-值”结构,也是用数组存储,数组下标就是“键”

//字典类
			function Dictionary(){
//				var tag=0;
				this.datastore=new Array();
				this.add=add;
				this.find=find;
				this.remove=remove;
				this.showAll=showAll;
				this.count=count;
				this.clear=clear;
				this.sortKey=sortKey;
				this.sortValue=sortValue;
//				this.next=next;
			}
//			//下一个键
//			function next(){
//				tag++;
//				console.log(tag);
//				if(tag<this.datastore.count) this.tag++;
//				var flag=0;
//				for(var key in this.datastore)
//				{
//					if(flag==tag) 
//					{	console.log(key+"->"+ this.datastore[key]);
//						break;
//					}
//					else flag++;
//				}
//				return tag;
//			}
			//按键增加
			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(var key in this.datastore){
					console.log(key+"->"+this.datastore[key]);
				}
			}
			//统计个数
			function count(){
				var n=0;
				//不能用length,因为当键的类型为字符串是,length属性就不管用了
//				n=this.datastore.length; 
				for(var key in this.datastore) n++;
				return n;
			}
			//清除所有的键值
			function clear(){
				for(var key in this.datastore){
					delete this.datastore[key];
				}
			}
			//按键排序显示,但是并不能对原数组进行排序
			function sortKey(){
				//对键值数组来说,sort方法同样无效
				//对键进行排序,返回的也是新的数组(键,并不包含值),并且对原数组对没有任何影响
				console.log("按键排序:");
				var sidc=Object.keys(this.datastore).sort();
				for(var i=0;i<sidc.length;i++){
					console.log(sidc[i]+"->"+this.datastore[sidc[i]]);
				}
			}
			//按值排序显示,如果有更好的方法请告知
			function sortValue(){
				//创建值数组存放只原数组中的值
				var i=0;
				var arry_temp=[];
				for(var key in this.datastore){
					arry_temp[i]=this.datastore[key];	
					i++;
				}
				
				//对值数组进行排序
				arry_temp.sort(function(a,b){return a-b});
				console.log("对值排序:");
				
				//从原数组中找与值数组值相等的
				for(i=0;i<arry_temp.length;){
					for(key in this.datastore){
						if(this.datastore[key]==arry_temp[i]){
						console.log(key+"->"+this.datastore[key]);
						i++;
						}	
					}
				}	
			}
			var pbook=new Dictionary();
			pbook.add("mike","923");
			pbook.add("mike2","345");
			pbook.add("mike3","567");
			pbook.add("mike4","789");
			pbook.add("amike4","789");
			
			console.log(pbook.find("mike2"));
			pbook.remove("mike2");
			pbook.showAll();
			console.log(pbook.count());
			pbook.sortKey();
			pbook.sortValue();


猜你喜欢

转载自blog.csdn.net/prince_fmx/article/details/78176961