JS数据结构:字典

字典

字典(Dictionary)是一种以 键-值对 形式存储数据的数据结构 ,就如同我们平时查看通讯录一样,要找一个电话,首先先找到该号码的机主名字,名字找到了,紧接着电话号码也就有了。这里的键就是你用来查找的东西,本例中指代的就是名字,值就是查找得到的结果,也就是对应的电话号码。
其实,JavaScript 中的 Object 类就是以字典的形式设计的,下面我们将会借助 Object 类的特性,自主实现一个 Dictionary 类,让这种字典类型的对象使用起来更加方便。

字典的创建

class Dictionary {
    constructor() {
        this.items = {};
    }

    // 向字典中添加新元素
    set( key, value ) {
        this.items[key] = value;
    }

    // 如果某个键值存在于这个字典中,则返回true,反之则返回false
    has( key ) {
        return key in this.items;
    }

    // 通过键值查找特定的数值并返回
    get( key ) {
        return this.has(key) ? this.items[key] : undefined;
    }

    size() {
        return Object.keys(this.items).length;
    }

    // 将这个字典中的所有元素全部删除
    clear() {
        this.items = {};
    }

    // 通过使用键值来从字典中移除键值对应的数据值
    delete( key ) {
        if( this.has(key) ) {
            delete this.items[key];
            return true;
        }

        return false;
    }

    // keys方法返回在Dictionary类中所有用于标识值的键名
    keys() {
        return Object.keys( this.items );
    }

    // 将字典所包含的所有数值以数组形式返回
    values() {
        let values = [];
        for( let i = 0, keys = Object.keys(this.items); i < keys.length; i++ ) {
            values.push( this.items[keys[i]] );
        }

        return values;
    }

    getItems() {
        return this.items;
    }
}

使用字典

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>字典</title>
    </head>
    <body>
        <p>在字典中,存储的是[键,值] 对,其中键名是用来查询特定元素的。</p>

        <script type="text/javascript" src="Dictionary.js"></script>
        <script type="text/javascript">
            var dictionary = new Dictionary();
            dictionary.set( 'Gandalf', 'gandalf@email.com' );
            dictionary.set( 'John', 'johnsnow@email.com' );
            dictionary.set( 'Tyrion', 'tyrion@email.com' );

            console.log( dictionary.has('Gandalf') );   // true
            console.log( dictionary.size() );

            console.log( dictionary.keys() );
            console.log( dictionary.values() );
            console.log( dictionary.get('Tyrion') );
        </script>
    </body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容