JS数据结构二次封装我们的数组

GitHub更新 https://github.com/liangfengbo/javascript-data-structures-and-algorithms

目录

  1. 新建一个myArray类
  2. 在这个类上初始化构造函数
  3. 增加数组成员方法
  4. 增加数组添加元素方法
  5. 增加数组中移除元素方法
  6. 增加数组中查询元素和修改元素方法
  7. 增加数组中包含,搜索方法
  8. 测试封装数组的方法
  9. 方法说明
  10. 完整二次封装数组代码

一、新建一个myArray类

class myArray {
    
}

二、在这个类上初始化构造函数

/**
 * 初始化构造函数
 * @param capacity 容量
 */
constructor(capacity) {
    // 初始化arr变量
    this.arr = capacity === undefined ? [] : new Array(capacity);
    // 数组长度
    this.length = 0;
    // 数组容量
    this.capacity = capacity;
}

三、增加数组成员方法

// 获取数组的长度
getLength() {
    return this.length;
}

// 获取数组的容量
getCapacity() {
    return this.arr.length;
}

// 判断数组是否为空
isEmpty() {
    return this.length === 0;
}

四、增加数组添加元素方法

/**
 * 在数组中在index插入一个新的元素e
 * @param index 索引
 * @param e 元素
 * 原理:
 * 首先在传进来index索引的位置向后面移动一位,
 * 然后把该index索引腾空出来放进传入的新的元素e,
 * 最后维护一下length,长度加1
 */
add(index, e) {

    if (this.length === this.arr.length) {
        throw new Error('Add failed. Array is full.')
    }

    if (index < 0 || index > this.length) {
        throw new Error('Add failed. Request index >= 0 and index <= length');
    }

    for (let i = this.length - 1; i >= index; i--) {
        this.arr[i + 1] = this.arr[i];
    }

    this.arr[index] = e;
    this.length++;
}


// 向数组首位添加一个新元素e
addFirst(e) {
    this.add(0, e)
}

// 向数组所有的元素后面添加一个新元素e
addLast(e) {
    this.add(this.length, e);
}

五、增加数组中移除元素方法

/**
 * 从数组中删除index位置的元素,返回删除的元素
 * @param index
 * @returns {*}
 * 原理:
 * 首先找到索引index的位置,
 * 然后把索引后面的元素都向前移动一位,其实是把索引后面的翻盖前面一位的元素
 * 最后维护一下length,减一
 *
 */
remove(index) {
    if (index < 0 || index >= this.length) {
        throw new Error('Remove failed. Request index >= 0 and index <= length');
    }

    let ret = this.arr[index];
    for (let i = index + 1; i < this.length; i++) {
        this.arr[i - 1] = this.arr[i];
    }
    this.length--;

    return ret;
}

// 从数组中删除第一个元素,返回删除的元素
removeFirst() {
    return this.remove(0)
}

// 从数组中删除最好个元素,返回删除的元素
removeLast() {
    return this.remove(this.length - 1)
}

// 从数组中删除元素e
removeElement(e) {
    let index = this.findIndex(e);
    if (index != -1) {
        this.remove(index);
    }
}

六、增加数组中查询元素和修改元素方法

// 获取index索引位置的元素
get(index) {
    if (index < 0 || index >= this.length) {
        throw new Error('Get failed. Index is illegal.');
    }
    return this.arr[index];
}

// 修改index索引的元素e
set(index, e) {
    if (index < 0 || index >= this.length) {
        throw new Error('Get failed. Index is illegal.');
    }
    this.arr[index] = e;
}

七、增加数组中包含,搜索方法

// 查询数组是否包含e元素
contains(e) {
    for (let i = 0; i < this.length; i++) {
        if (this.arr[i] === e) {
            return true;
        }
    }
    return false;
}

// 查找数组中元素所在的所在的索引,如果不存在e,则返回-1
findIndex(e) {
    for (let i = 0; i < this.length; i++) {
        if (this.arr[i] === e) {
            return i;
        }
    }
    return -1;
}

// 把数组转换为字符串,并返回结果
toString() {
    let res = "";
    console.log(`Array: length = ${this.length}, capacity = ${this.capacity}.`);

    res += "[";
    for (let i = 0; i < this.length; i++) {
        res += this.arr[i];
        if (i !== this.length - 1) {
            res += ', '
        }
    }
    res += "]";

    return res.toString();
}

八、测试封装数组的方法

// 使用我们的类数组,声明一个容量为20的数组
let arr = new myArray(20);
// 首位增加数据
arr.addFirst('波波');
console.log(arr.toString());
// 输出:Array: length = 1, capacity = 20.
// 输出:[波波]

for (let i = 0; i < 10; i++) {
    arr.addLast(i)
}
console.log(arr.toString());
// 输出:Array: length = 11, capacity = 20.
// 输出:[波波, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(arr.findIndex(4)); // 5

// ...

九、方法说明

方法描述参数参数说明示例
getLength返回数组的长度 getLength()
getCapacity返回数组的容量 getCapacity()
isEmpty判断数组是否为空,返回布尔值 isEmpty()
addFirst向数组首位添加一个新元素e新元素addFirst(e)
addLast向数组所有的元素后面添加一个新元素e新元素addLast(e)
add在数组中在index插入一个新的元素eindex, eindex索引,e 新元素add(index, e)
remove从数组中删除index位置的元素,返回删除的元素index索引remove(index)
removeFirst从数组中删除第一个元素,返回删除的元素 removeFirst()
removeLast从数组中删除最后的元素,返回删除的元素 removeLast()
removeElement从数组中删除元素ee删除的元素eremoveElement(e)
get获取index索引位置的元素index索引get(index)
set修改index索引的元素eindex, eindex 索引,e新替换的元素set(index, e)
contains查询数组是否包含e元素e查询包含的元素contains(e)
findIndex查找数组中e元素所在的所在的索引,如果不存在e,则返回-1e查询的元素findIndex(e)
toString返回数组格式化数据 toString()

十、完整二次封装数组代码

class myArray {
    /**
     *  初始化构造函数
     * @param capacity 容量
     */
    constructor(capacity) {
        // 初始化arr变量
        this.arr = capacity === undefined ? [] : new Array(capacity);
        // 数组长度
        this.length = 0;
        // 数组容量
        this.capacity = capacity;
    }

    // 获取数组的长度
    getLength() {
        return this.length;
    }

    // 获取数组的容量
    getCapacity() {
        return this.arr.length;
    }

    // 判断数组是否为空
    isEmpty() {
        return this.length === 0;
    }

    addFirst(e) {
        this.add(0, e)
    }

    // 向所有的元素后面添加一个新元素
    addLast(e) {
        this.add(this.length, e);
    }

    /**
     * 在数组中在index插入一个新的元素e
     * @param index 索引
     * @param e 元素
     * 原理:首先在传进来index索引的位置向后面移动一位,
     * 然后把该index索引腾空出来放进传入的新的元素e,
     * 最后维护一下length,长度加1
     */
    add(index, e) {

        if (this.length === this.arr.length) {
            throw new Error('Add failed. Array is full.')
        }

        if (index < 0 || index > this.length) {
            throw new Error('Add failed. Request index >= 0 and index <= length');
        }

        for (let i = this.length - 1; i >= index; i--) {
            this.arr[i + 1] = this.arr[i];
        }

        this.arr[index] = e;
        this.length++;
    }

    /**
     * 从数组中删除index位置的元素,返回删除的元素
     * @param index
     * @returns {*}
     * 原理:
     * 首先找到索引index的位置,
     * 然后把索引后面的元素都向前移动一位,其实是把索引后面的翻盖前面一位的元素
     * 最后维护一下length,减一
     *
     */
    remove(index) {
        if (index < 0 || index >= this.length) {
            throw new Error('Remove failed. Request index >= 0 and index <= length');
        }

        let ret = this.arr[index];
        for (let i = index + 1; i < this.length; i++) {
            this.arr[i - 1] = this.arr[i];
        }
        this.length--;

        return ret;
    }

    // 从数组中删除第一个元素,返回删除的元素
    removeFirst() {
        return this.remove(0)
    }

    // 从数组中删除最好个元素,返回删除的元素
    removeLast() {
        return this.remove(this.length - 1)
    }

    // 从数组中删除元素e
    removeElement(e) {
        let index = this.findIndex(e);
        if (index != -1) {
            this.remove(index);
        }
    }


    // 获取index索引位置的元素
    get(index) {
        if (index < 0 || index >= this.length) {
            throw new Error('Get failed. Index is illegal.');
        }
        return this.arr[index];
    }

    // 修改index索引的元素e
    set(index, e) {
        if (index < 0 || index >= this.length) {
            throw new Error('Get failed. Index is illegal.');
        }
        this.arr[index] = e;
    }

    // 查询数组是否包含e元素
    contains(e) {
        for (let i = 0; i < this.length; i++) {
            if (this.arr[i] === e) {
                return true;
            }
        }
        return false;
    }

    // 查找数组中元素所在的所在的索引,如果不存在e,则返回-1
    findIndex(e) {
        for (let i = 0; i < this.length; i++) {
            if (this.arr[i] === e) {
                return i;
            }
        }
        return -1;
    }

    // 把数组转换为字符串,并返回结果
    toString() {
        let res = "";
        console.log(`Array: length = ${this.length}, capacity = ${this.capacity}.`);

        res += "[";
        for (let i = 0; i < this.length; i++) {
            res += this.arr[i];
            if (i !== this.length - 1) {
                res += ', '
            }
        }
        res += "]";

        return res.toString();
    }
}

// 测试
// 使用我们的类数组,声明一个容量为20的数组
let arr = new myArray(20);
// 首位增加数据
arr.addFirst('波波');
console.log(arr.toString());
// 输出:Array: length = 1, capacity = 20.
// 输出:[波波]

for (let i = 0; i < 10; i++) {
    arr.addLast(i)
}
console.log(arr.toString());
// 输出:Array: length = 11, capacity = 20.
// 输出:[波波, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log(arr.findIndex(4)); // 5

// ...上面的方法都可以测试使用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值