数据结构与算法JavaScript描述[第七章](字典)

//字典基类
    function Dictionary() {
        this.dataStore = [];
        this.add = function (key,value) {
            this.dataStore[key] = value;
        };
        this.find = function (key) {
            return this.dataStore[key];
        };
        this.remove = function (key) {
            delete this.dataStore[key];
        };
        this.showAll = function () {
            for(var key in Object.keys(this.dataStore).sort()){
                console.log(Object.keys(this.dataStore)[key] +'->'+ this.dataStore[Object.keys(this.dataStore)[key]]);
            }
        };
        this.count = function () {
            return Object.keys(this.dataStore).length;
        };
        this.clear = function () {
            Object.keys(this.dataStore).forEach(function (key) {
                delete this.dataStore[key];
            },this);
        };
    };


1.写一个程序,该程序从一个文本文件中读入名字和电话号码,然后将其存入一个字典。
    该程序需包含如下功能:显示耽搁电话号码,显示所有电话号码,增加新电话号码,

删除电话号码,清空所有电话号码。

    var AddressBook = function () {};
    AddressBook.prototype = new Dictionary();
    //显示一个电话号码
    AddressBook.prototype.showSingle = function (name) {
        console.log(this.find(name));
    };
    var addressBook = new AddressBook();
    //增加新的电话测试
    addressBook.add('zhang',133);
    addressBook.add('qing',144);
    addressBook.add('dong',155);
    //删除一个测试
    addressBook.remove('qing');
    addressBook.showAll();
    addressBook.showSingle('zhang');
    //清除所有测试
    addressBook.clear();
    //显示所有测试
    addressBook.showAll();

2.使用Dictionary类写一个程序,该程序用来存储一段文本中各个单词出现的次数。该程序显示每个单词出现的次序,
但每个单词只显示一次。比如下面一段话‘the brown fox jumped over the blue fox’程序的输出应为:
the:2
brown:1
jumped:1
over:1
blue:1

    var Word = function () {};

    Word.prototype = new Dictionary();

    //添加统计
    Word.prototype.addCount = function (key) {
        this.dataStore[key] = (this.dataStore[key])?this.dataStore[key]+1:1;
    };
    //解析句子
    Word.prototype.analysis  = function (sentence) {
        var words = sentence.split(' ');
        for(var key  in words){
            this.addCount(words[key]);
        }
    };
    //显示所有元素
    Word.prototype.showAll = function () {
        for(var key  in this.dataStore){
            console.log(key+':'+this.dataStore[key]);
        }
    };
    var word = new Word();
    word.analysis('I am an apple am a person I');
    word.showAll();

3.修改练习2,使单词按字母顺序显示。
 //按顺序显示所有元素
    Word.prototype.showAllBySort = function () {
        var keys = Object.keys(this.dataStore).sort();
        for(var key  in keys){
            console.log(keys[key]+':'+this.dataStore[keys[key]]);
        }
    };
    word.showAllBySort();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值