js实现HashTable类

93 阅读1分钟

js实现HashTable类

模拟一个HashTable类,该类上注册四个方法:add、remove、contains、length方法,其中使用push模拟add,splice模拟remove,四个方法均注册在原型上
// 1. 先在构造函数中定义一个数组
function HashTable() {
    this.value = [];
}
// 2. 在构造函数原型上添加“添加”方法
HashTable.prototype.add = function(val) {
    this.value.push(val);
}
// 3. 在构造函数原型上添加“移除”方法,按照下标来移除元素
HashTable.prototype.remove = function(index) {
    this.value.splice(index, 1);
}
// 4. 在构造函数原型上添加“包含”方法
HashTable.prototype.contains = function(val) {
    var preValue = this.value;
    for (var i = 0; i < preValue.length; i++) {
        if (val == preValue[i]) {
            return true;
        }
    }
    return false;
}
// 5. 在构造函数原型上添加“对象长度”方法
HashTable.prototype.length = function() {
    return this.value.length;
}

hash = new HashTable(); // 创建一个新对象
hash.add(1); // 给对象添加值
hash.add(2);
console.log(hash.length()); // 2
console.log(hash.contains(1)); // true
hash.remove(1); //利用下标来移除元素
console.log(hash.length()); // 1
console.log(hash.contains(1)); // false