JS数组增删的原理,自己定义方法实现

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

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

    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( )方法,添加一个元素到数组末尾

    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( )方法,删除数组第一个元素

    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( )方法,添加一个元素到数组开头

    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]

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

你可能感兴趣的:(javascript,前端,开发语言)