JS数组增删方法的原理,使用原型定义

大家有没有想过,数组有增删的方法,那实现的原理是什么?我们可以自己定义方法去实现增删数组吗?让我为大家介绍一下吧!

利用数组的原型对象,让所有数组都可以使用这个方法

1.实现pop( )方法,删除数组最后一个元素

javascript 复制代码
    Array.prototype.pops = function() {
        // 原型对象的this指向使用者
        // 我们把数组的长度给砍掉,就实现了pop方法
        this.length = this.length-1
    }
    const arr = [1,2,3,4]
    // 方法定义成功
    arr.pops()
    console.log(arr)//[1,2,3]

2.实现push( )方法,添加一个元素到数组末尾

javascript 复制代码
    Array.prototype.pushs = function(user) {
        // 因为我们索引从0开始,正好数组[数组长度]可以添加一个新值到末尾
        this[this.length] = user
    }
    const arr = [1,2,3,4]
    // 定义成功
    arr.pushs(5)
    console.log(arr) //[1,2,3,4,5]

3.实现shift( )方法,删除数组第一个元素

javascript 复制代码
    Array.prototype.shifts = function () {
        //我们该如何实现呢?我们可以交换数组元素位置,利用下标
        // 我们循环数组,这里我们为什么要减1,是因为我们换位置只需要换this.length-1次
        for (let i = 0; i < this.length - 1; i++) {
            this[i] = this[i + 1]
        }
        // 还是要减长度,第一个元素已经到了最后,我们直接把长度砍掉一个
        this.length = this.length - 1
    }
    const arr = [1, 2, 3, 4]
    // 定义成功
    arr.shifts()
    console.log(arr) //[2,3,4]

4.实现unshift( )方法,添加一个元素到数组开头

javascript 复制代码
    Array.prototype.unshifts = function(user) {
        // 增加长度 现在我们多出一个"" [""]
        this.length = this.length + 1
        // 我们现在循环,把所有的元素外后移动
        // 因为我们把数组长度增加了1,我们这需要减1
        // 假设我们现在arr = [1,2,3,4],外加一个长度变成了[1,2,3,4,""]
        // 我们从最后开始,一个一个往后移
        for(let i= this.length - 1;i>=0;i--) {
            this[i] = this[i-1]
        }
        // this[0]没有值我们现在赋值给this[0]
        this[0] = user
    }
    const arr = [1,2,3,4]
    // 定义成功
    arr.unshifts(0)
    console.log(arr) //[0,1,2,3,4]

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

相关推荐
独泪了无痕38 分钟前
Lodash-JavaScript的实用工具库
前端·javascript
有趣的老凌39 分钟前
用 Vibe Coding 搭了一个完整小程序「一定能成」
前端·javascript·后端
kyriewen11 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_233313 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
山河木马14 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
天蓝色的鱼鱼15 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷16 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花16 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷16 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全