第七章(字典)

来源:互联网 发布:大津算法 opencv 编辑:程序博客网 时间:2024/06/06 01:16

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

//字典类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();


原创粉丝点击