0

0

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

不言

不言

发布时间:2018-07-25 10:01:50

|

1456人浏览过

|

来源于php中文网

原创

本篇文章分享给大家的内容是关于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插入一个新的元素e index, e index索引,e 新元素 add(index, e)
remove 从数组中删除index位置的元素,返回删除的元素 index 索引 remove(index)
removeFirst 从数组中删除第一个元素,返回删除的元素

removeFirst()
removeLast 从数组中删除最后的元素,返回删除的元素

removeLast()
removeElement 从数组中删除元素e e 删除的元素e removeElement(e)
get 获取index索引位置的元素 index 索引 get(index)
set 修改index索引的元素e index, e index 索引,e新替换的元素 set(index, e)
contains 查询数组是否包含e元素 e 查询包含的元素 contains(e)
findIndex 查找数组中e元素所在的所在的索引,如果不存在e,则返回-1 e 查询的元素 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的模块化分析(命名空间)    

小麦企业网站展示系统1.1
小麦企业网站展示系统1.1

小麦企业网站展示系统介绍:一、安装使用将xiaomai.sql导入数据库二、后台登录后台帐号,密码默认都是admin,config.php 配置文件可根据自行需要修改,IP地址,数据库用户名,密码,及表名后台目录默认admin,支持自行任意修改目录名三、注意事项1 本源码完全免费,采用伪静态,减少不必要的源码重复,速度更快,支持二次开发。2、注明本程序编码为UTF8,如发生乱码,请注意修改编码3、

下载

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

相关专题

更多
C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

10

2026.01.23

php远程文件教程合集
php远程文件教程合集

本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

29

2026.01.22

PHP后端开发相关内容汇总
PHP后端开发相关内容汇总

本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

21

2026.01.22

php会话教程合集
php会话教程合集

本专题整合了php会话教程相关合集,阅读专题下面的文章了解更多详细内容。

21

2026.01.22

宝塔PHP8.4相关教程汇总
宝塔PHP8.4相关教程汇总

本专题整合了宝塔PHP8.4相关教程,阅读专题下面的文章了解更多详细内容。

13

2026.01.22

PHP特殊符号教程合集
PHP特殊符号教程合集

本专题整合了PHP特殊符号相关处理方法,阅读专题下面的文章了解更多详细内容。

11

2026.01.22

PHP探针相关教程合集
PHP探针相关教程合集

本专题整合了PHP探针相关教程,阅读专题下面的文章了解更多详细内容。

8

2026.01.22

菜鸟裹裹入口以及教程汇总
菜鸟裹裹入口以及教程汇总

本专题整合了菜鸟裹裹入口地址及教程分享,阅读专题下面的文章了解更多详细内容。

55

2026.01.22

Golang 性能分析与pprof调优实战
Golang 性能分析与pprof调优实战

本专题系统讲解 Golang 应用的性能分析与调优方法,重点覆盖 pprof 的使用方式,包括 CPU、内存、阻塞与 goroutine 分析,火焰图解读,常见性能瓶颈定位思路,以及在真实项目中进行针对性优化的实践技巧。通过案例讲解,帮助开发者掌握 用数据驱动的方式持续提升 Go 程序性能与稳定性。

9

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
React 教程
React 教程

共58课时 | 4万人学习

TypeScript 教程
TypeScript 教程

共19课时 | 2.4万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号