算法与数据结构——字典

字典

字典是一种以键 - 值对形式存储数据的数据结构,就像电话号码簿里的名字和电话号码一 样。要找一个电话时,先找名字,名字找到了,紧挨着它的电话号码也就找到了。

JavaScript 的 Object 类就是以字典的形式设计的。我们尝试利用obj的特点实现一个带有字典基本方法的字典类。

一、Dictionary类

为了方便对字典进行排序,我们要基于数组进行扩展,但要注意数组也是特殊的对昂。

function Dictionary() { 
	this.datastore = new Array(); 
}

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

function add(key, value) { 
	this.datastore[key] = value; 
}

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

function find(key) { 
	return this.datastore[key]; 
}

1.3 定义remove()
以键作为参数,同时删掉键和与其关联的值

function find(key) { 
	delete this.datastore[key];
}

1.4 showAll()
显示所有的键-值对

function showAll() { 
	for(var key in Object.keys(this.datastore)) { 
		console.log(key + " -> " + this.datastore[key]); 
		//调用 Object 类的 keys() 方法可以返回传入参数中存储的所有键。
	} 
}

二、Dictionary类的辅助方法

2.1 count()——字典中的元素个数

注意,这里利用Object.key()而不是.length,是因为当key是字符串(arr['nihao'])时,length属性不会记录此数据。

function count() { 
	var n = 0; 
	for(var key in Object.keys(this.datastore)) {
		++n; 
	}
	return n; 
}

2.2 clear()——清空字典

function clear() { 
	for(var key in Object.keys(this.datastore)) {
		delete this.datastore[key]
	} 
}

三、对Dictionary类进行排序

key-value的形式使得排序并不是必须得,但如果我们希望看到一个有序的字典,怎么办?

可以使用 Object.keys() 函数解决这个问题,下面是重新定义的 showAll() 方法:

function showAll() { 
	for(var key in Object.keys(this.datastore).sort()) { 
		print(key + " -> " + this.datastore[key]); 
	} 
} 

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

字典类的完整代码

function Dictionary() { 
	this.datastore = new Array(); 
	this.add = add; 
	this.find = find; 
	this.remove = remove; 
	this.showAll = showAll; 
	this.count = count; 
	this.clear = clear; 
}
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 each (var key in Object.keys(this.datastore)) { 
		print(key + " -> " + this.datastore[key]); 
	} 
}
function count() { 
	var n = 0; 
	for each (var key in Object.keys(this.datastore)) { 
		++n; 
	}
	return n; 
}
function clear() { 
	for each (var key in Object.keys(this.datastore)) { 
		delete this.datastore[key]; 
	} 
}
发布了263 篇原创文章 · 获赞 40 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/jbj6568839z/article/details/104754068
今日推荐