您的位置:首页 > 理论基础 > 数据结构算法

JS数据结构与算法--字典

2016-04-26 19:04 381 查看
1.字典是一种以键-值对形式存储数据的数据结构,(如,电话号码薄里面的名字和电话号码,要找一个电话时,先找名字。),这里的键是指你用来查找的东西,值就是你查找到的结果。

2.Dictionary 类的基础是Array类,而不是Object类。

开始定义Dictionary 类:

      function Dictionary
(){

       this.datastore=new
Array();

            }

先定义add()方法,该方法接受两个参数:键和值。键是值在字典中的索引,代码如下:

        function
add (key){

              this.datastore[key]=value;

            }

接下来定义find()方法,该方法以键作为参数,返回和其关联的值。代码如下:

        function
find (key){

              return
this.datastore[key];

            }

从字典中删除键-值对需要使用delete。该函数同时删除键和与其关联的值。代码:

            function
remove (key){

              delete  this.datastore[key];

            }

最后,显示字典中所有的键-值对:

              function
showAll(){

 for(var
key in
Object.keys(this.database)){

 print(key
+ "->" +
this.datastore[key]);

 }

 }

测试:

var pbook= new Dictionary ();

pbook.add("Mike","123");

pbook.add("David","345");

pbook.add("Cynthia","456");

print(pbook.find("David"));

pbook.remove("David");

pbook.showAll();

2  Dictionary
类的辅助方法

定义字典中的元素个数函数

    function
count(){

 var
n=0;

 for(var
key in
Object.keys(this.datastore)){

 ++n;

 }

 return
n;

 }

为什么不用length属性呢,因为当键的类型为字符串时,length属性就不管用啦。

Clear()是另外一个辅助函数

function clear(key){

 for
each(var
key in
Object.keys(this.datastore)){

 delete  this.datastore[key];

 }

 }

3
为Dictionary类添加排序功能

字典的主要用途是通过键取值,我们无须太关心数据在字典中的实际存储顺序,然而,很多人都希望看到一个有序的字典。

只要重新定义showAll()方法:

function showAll(){

 for(var
key in
Object.keys(this.database).sort()){

 print(key
+ "->" +
this.datastore[key]);

 }

 }

该定义和之前的唯一区别是:从数组datastore拿到键后,调用sort()方法对键值重新排序

 

Dictionary.js

function Dictionary
(){

              this.datastore=new
Array();

            }

 function
add (key){

              this.datastore[key]=value;

            }

 function
find (key){

              return
this.datastore[key];

            }

 function
remove (key){

              delete  this.datastore[key];

            }

 function
showAll(){

 for(var
key in
Object.keys(this.database).sort()){

 print(key
+ "->" +
this.datastore[key]);

 }

 }

 function
count(){

 var
n=0;

 for(var
key in
Object.keys(this.datastore)){

 ++n;

 }

 return
n;

 }

             function
clear(key){

 for
each(var
key in
Object.keys(this.datastore)){

 delete  this.datastore[key];

 }

 }

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript css html