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]

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

相关推荐
NiceCloud喜云3 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby4 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing4 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩4 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手4 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车4 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋4 小时前
C++14特性
开发语言·c++·c++14特性
Front思5 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai
JAVA社区5 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子6 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php