首页
学习
活动
专区
圈层
工具
发布

数据结构于JS也可以成为CP(六)字典

Hello小伙伴们大家好,今天我们继续下一个数据结构,前面的数据结构所存储的数据都是单元素,但是如果我们想对一对数据进行存储该用什么呢?这时候就要请出字典了,字典是一种键-值对形式的数据结构,有没有想起什么,没错object就是以字典为基础的呢。

字典的实现

相同的,字典的基础也是Array。我们想一下如果拥有一个字典,我们希望有什么方法呢?我们希望能向其中添加元素、删除元素以及查看元素,而实现这些的前提首先要有一个数组来存储元素,除此,我们还需要对字典长度进行计数。因此我们需要定义一个Array、需要add方法、remove方法、find方法、showAll方法、count方法等。细心的小伙伴会发现这里.length的结构貌似有时候不好使了呢,因为当键值是字符串的时候,电脑就凌乱了,到底是字符串的长度还是字典长度呢,所以不好用了呢!下面我们看看具体实现吧:

代码语言:javascript
复制
function Dictionary() {
  this.add = add; 
  this.datastore = new Array(); 
  this.find = find;
  this.remove = remove;
  this.showAll = showAll;
  this.count = count;
  this.clear = clear;
}
function add(key, value) {
  his.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.datastore)) {
      print(key + " -> " + this.datastore[key]);
  }
}
function count() {
  var n = 0;
  for(var key in Object.keys(this.datastore)) {
     ++n;
}
return n; }
function clear() {
  for (var key in Object.keys(this.datastore)) {
     delete this.datastore[key];
  }
}

字典的使用

1)字典定义完了,我们来看看字典究竟好在哪里,又怎么用呢?

代码语言:javascript
复制
var rabbitDic = new Dictionary();
rabbitDic.add("rabbit1", "white");
rabbitDic.add("rabbit2", "yellow");
rabbitDic.add("rabbit3", "grey");
rabbitDic.find("rabbit3");
rabbitDic.remove("rabbit1");
rabbitDic.showAll();

2)字典的排列:我们不能够直接通过sort函数进行排列,而是应该对键值使用sort函数排列。

代码语言:javascript
复制
function showAll() {
  for(var key in Object.keys(this.datastore).sort()) {
     print(key + " -> " + this.datastore[key]);
  }
}
下一篇
举报
领券