• 技术文章 >web前端 >js教程

    js二次封装数组的使用介绍(代码)

    不言不言2018-07-25 10:01:50原创703
    本篇文章分享给大家的内容是关于JS数据结构二次封装我们的数组 ,内容很详细,接下来我们就来看看具体的内容,希望可以帮助到大家。

    一、新建一个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
    
    // ...上面的方法都可以测试使用。

    相关推荐:

    js的模块化分析(命名空间)

    什么是JS变量对象?JS变量对象详解以及注意事项

    以上就是js二次封装数组的使用介绍(代码)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:javascript
    上一篇:2018 js 回顾:框架存在的根本原因原来是这些 下一篇:经典_用js快速实现鼠标和键盘选择下拉菜单(代码详解)
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• JavaScript的Symbol类型、隐藏属性及全局注册表详解• 18个常见angular面试题(附答案分析)• 什么是消息队列?node中如何使用消息队列?• 浅析IDEA中如何开发Angular• 整理总结JavaScript常见的BOM操作
    1/1

    PHP中文网