数组API自己重写

1.pop()

 // 1.pop() 删除末尾的数
        Array.prototype.mypop = function () {
            let num = this[this.length - 1]
            this.length--;//数组最后一个数删除(重要)
            return num
        }

2.push()

   //2.push() 从末尾添加数  
        Array.prototype.mypush = function () {
            this[this.length] = arguments[0];
            return this.length;
        }

3.shift()

Array.prototype.myshift = function () {
            let num = this[0];
            for (let i = 1; i < this.length; i++) {
                this[i - 1] = this[i]
            }//将数组往前移一位
            this.length--;
            return num;
        }

4.unshift()

  // 4.unshift() 数组前添加元素
        Array.prototype.myunshift = function () {
            let len = this.length;
            this[len] = 0;
            for (let i = len; i > 0; i--) {
                this[i] = this[i - 1];
                this[i - 1] = arguments[0];
            }
            return this.length
        }

5.slice()

// 5.slice()截取数组
        Array.prototype.myslice = function () {
            let arr = [];//储存返回的数组

            //有两个参数时的情况
            if (arguments.length == 2) {
                if (arguments[0] > arguments[1]) return "error"  //第一个参数小于等于第二个参数
                if (arguments[0] < 0) return "error"             //第一个参数小于0
                for (let i = arguments[0]; i < arguments[1]; i++) {
                    arr.mypush(this[i])
                }//两个参数且正常
            }

            else {
                if (arguments[0] > 0) {
                    for (let i = arguments[0]; i < this.length; i++) { arr.mypush(this[i]) }//只有一个参数且为正数时,截取该数直到最后
                }
                if (arguments[0] < 0) {
                    for (let i = this.length - 1; i >= this.length - (-arguments[0]); i--) {
                        if (i < 0) continue
                        arr.mypush(this[i])
                    }
                }//只有一个参数且参数小于0时,从后面开始截取
            }
            return arr

        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值