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]

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

相关推荐
wuyoula3 分钟前
尹之盾企业版网络验证
服务器·开发语言·javascript·c++·人工智能·ui·c#
Via_Neo7 分钟前
区间dp算法
开发语言·javascript·算法
aq553560012 分钟前
Laravel 10.x重磅升级:PHP 8.1+新时代
开发语言·php·laravel
shaoFan114 分钟前
关于java 调用阿里千问大模型,流式返回,并返回给前端
java·前端·状态模式
秋雨梧桐叶落莳18 分钟前
iOS——Masonry约束内容整理
开发语言·学习·macos·ios·objective-c·cocoa
Hesionberger19 分钟前
LeetCode72.编辑距离(多维动态规划)
java·开发语言·c++·python·算法
❆VE❆23 分钟前
React基础篇(三):项目中 React 基础核心知识点实战
前端·javascript·react.js·前端框架
Hello--_--World25 分钟前
React 的核心设计理念是什么?并列举三大核心特性。
javascript·react.js·ecmascript
Momo__26 分钟前
contenteditable 深度剖析:让网页元素「活」起来
前端·html
Via_Neo26 分钟前
Bash Game
开发语言·bash