数据结构-字典(JavaScript)

直接上代码

function Dictionay() {
	this.datastore = new Array();
    this.add       = add;
    this.find      = find;
    this.remove    = remove;
    this.showAll   = showAll;
    this.clear     = clear;
    this.count     = count;
}

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 thisKeysArr = Object.keys(this.datastore).sort();
    for (var keyIndex in thisKeysArr) {
        var keyName = thisKeysArr[keyIndex];
        console.log(keyName, this.datastore[keyName]);
    }
}

function clear() {
    var thisKeysArr = Object.keys(this.datastore);//得到数字索引数组
    for (var keyIndex in thisKeysArr) {
        var keyName = thisKeysArr[keyIndex];
        delete this.datastore[keyName];
    }
}

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

var pbook = new Dictionay();
pbook.add("Raymond","123");
pbook.add('Mike', '123');
pbook.add('David', '345');
pbook.add('Cynthia', '456');
console.log("Number of entries:", pbook.count());
console.log("David's extension:", pbook.find("David"));
pbook.showAll();
pbook.clear();
console.log("Number of entries:", pbook.count());
pbook.remove('ddd');//未报错

运行结果如下:

Number of entries: 4
David's extension: 345
Cynthia 456
David 345
Mike 123
Raymond 123
Number of entries: 0

说明:
   showAll()方法中,最终可以得到有序字典。但是,sort()只对数字索引数组有效,对字符串索引的字典无效

参考文献

[1] [巴西]Loiane Groner. 学习JavaScript数据结构与算法(第2版)[M]. 人民邮电出版社,2017.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值