js 重构 shift/unshift

本文主要探讨了JavaScript中数组的重构技巧,重点分析了`shift`和`unshift`两个方法的使用,包括它们如何改变数组的首元素以及对数组索引的影响,帮助开发者更好地理解和应用这些方法进行数组操作。
摘要由CSDN通过智能技术生成

重构

- shift

        // 重构
		Array.prototype.myShift = function () {
            // 拿到数组第一个数
            var num = this[0];
            // 将数组的第二项赋值给第一项,第三项赋值给第二项...
            // this[0] = this[1];
            // this[1] = this[2];
            // this[2] = this[3];
            for(var i = 0;i<this.length;i++){
                this[i] = this[i+1];
            }
            // 通过length属性删除最后一项
            this.length = this.length-1;
            return num;
        };
        var arr = [1,2,3,4];
        var result = arr.myShift();
        console.log(arr);
        console.log(result);
  • unshift
        // 重构
		Array.prototype.myUnshift = function () {
            // 插入数之后的长度 = 原数组的长度 + 插入数的长度
            var len = this.length + arguments.length;

            // 将这个长度给了数组之后,数组会多出来相应的空槽
            this.length = len;

            // 将原数组中的数向后移动
            /*this[5] = this[3];
            this[4] = this[2];
            this[3] = this[1];
            this[2] = this[0];
            this[0] = arguments[0];
            this[1] = arguments[1];*/
            for(var i=this.length-1;i>=arguments.length;i--){  
                // this[this.length-1] = this[this.length-arguments.length-1] 
                this[i] = this[i-arguments.length];  
            }
            // 将需要插入的值赋值给数组前面
            for(var j=0;j<arguments.length;j++){
                this[j] = arguments[j];
            }
            return len;
        };
        var arr = [1,2,3,4];
        var result = arr.myUnshift(99,88,5,6,7,8);
        console.log(arr);
        console.log(result);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值