数据结构: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){
	this.dataStore[key] = value;
}
function find(key){
	return this.dataStore[key];
}
function remove(key){
	delete this.dataStore[key];
}
function showAll(){
	var keys = Object.keys(this.dataStore);
	//调用Object类的keys方法可以返回传入参数中存储的所有键
	for(var i in keys){
		console.log(keys[i] + "->" + this.dataStore[keys[i]]);
	}
}
function count(){
	var n = 0;
	for(var key in Object.keys(this.dataStore)){
		++n;
	}
	return n;
}
function clear(){
	var keys = Object.keys(this.dataStore);
	for(var i in keys){
		delete this.dataStore[keys[i]];
	}
}
//测试一下!
var books = new Dictionary();
books.add("math", "12");
books.add("english", "3");
books.add("chinese", "2");
books.add("pe", "12000");
console.log("字典中的元素个数:" + books.count());
console.log("english在字典中对应的值:" + books.find("english"));
books.showAll();
books.remove("chinese");
console.log("执行过删除元素操作后字典中的元素个数:" + books.count());
books.showAll();
books.clear();
console.log("字典中的元素个数:" + books.count());

运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值