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]

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

相关推荐
野槐44 分钟前
Electron开发
前端·javascript·electron
#做一个清醒的人44 分钟前
【Electron】开发两年Electron项目评估报告
前端·electron
lizhongxuan7 小时前
Claude Code 防上下文爆炸:源码级深度解析
前端·后端
紫金修道7 小时前
【DeepAgent】概述
开发语言·数据库·python
Via_Neo7 小时前
JAVA中以2为底的对数表示方式
java·开发语言
书到用时方恨少!7 小时前
Python multiprocessing 使用指南:突破 GIL 束缚的并行计算利器
开发语言·python·并行·多进程
cch89187 小时前
PHP五大后台框架横向对比
开发语言·php
天真萌泪8 小时前
JS逆向自用
开发语言·javascript·ecmascript
野生技术架构师8 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
柳杉8 小时前
震惊!字符串还能这么玩!
前端·javascript