JavaScript data structures and algorithms to achieve (c) hash table

(B) a hash table

Study Notes: coderwhy JavaScript implementation of data structures and algorithms courses

2. collection

2.1 feature set of

Here Insert Picture Description
Here Insert Picture Description

2.2 JavaScript packaging method

Here Insert Picture Description

2.2 set of common operations

Here Insert Picture Description
Here Insert Picture Description

Code Package common set of operations implemented 2.3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封装集合</title>
</head>
<body>
<script>
    // 封装集合类
    function Set() {
        // 属性
        this.items = {}  // 使用了js的object对象
        // 方法
        // add 方法
        Set.prototype.add = function (value) {
            // 判断集合中是否已经包含了该元素
            if(this.has(value)){
                return false; // 添加失败
            }else {
                // 将元素添加到集合中
                this.items[value] = value; // 这里是把属性和属性值都设置为要添加的元素
                return true;
            }
        } ;
        // has方法
        Set.prototype.has = function (value) {
            return this.items.hasOwnProperty(value);
        };
        // remove方法
        Set.prototype.remove = function (value) {
            // 1. 该集合中是否包含该元素
            if(!this.has(value)){
                return false;
            }else{
                // 2. 将元素从属性中删除
                delete this.items[value];
                return true;
            };

        };
        // clear 方法
        Set.prototype.clear = function () {
            this.items = {}
        };

        // size方法
        Set.prototype.size = function () {
            return Object.keys(this.items).length;
        };

        // 获取集合中所有的值
        Set.prototype.values = function () {
            return Object.keys(this.items);  // 获取object中的所有key
        }
    };

    // 测试Set类

    // 1. 创建Set类对象
    var set = new Set();

    // 2. 添加元素
    alert(set.add('abc'));
    alert(set.add('abc'));
    alert(set.add('cba'));
    alert(set.add('nba'));
    alert(set.add('mba'));
    alert(set.values());

    // 3. 删除元素
    alert(set.remove('mba'));
    alert(set.remove('mba'));
    alert(set.values());

    // 4. has方法
    alert(set.has('abc'));
    alert(set.has('aaabc'));

    // 5. 获取元素的个数
    alert(set.size());

    // 6. clear 方法
    set.clear();
    alert(set.size());
</script>
</body>
</html>
Published 17 original articles · won praise 0 · Views 663

Guess you like

Origin blog.csdn.net/weixin_43545225/article/details/104301966