js数组方法的实现

一:会改变原数组的方法:不会返回新数组

1:push():像数组中最后一位添加一个或多个元素,返回新的长度
 		Array.prototype.myPush = function (...value) {
   
            //  console.log(value, 'plpl');// 返回的是数组
            value.forEach((item) => {
   
                //  this:该数组
                this[this.length] = item

            })
            return this.length
        }
        let arr = [1, 2, 3]
        arr.myPush(4, 5, 6)
2:pop():删除数组中的最后一个元素,返回该元素,有参数还是没参数都是一样
   Array.prototype, myPop = function () {
   
            if (!this.length) return undefined
            let end = this[this.length - 1] // 最后一个元素
            this[this.length - 1] = null
            this.length = this.length - 1
            return end

        }
        let arr1 = [1, 2, 3]
3:shift():删除数组的第一个元素,并返回该元素
    Array.prototype.myshift = function () {
   
            if (!this.length) return undefined
            let start = this[0]
            this[0] = null
            this.length = this.length - 1
            return start
        }
4:unshift():向数组的开头添加一个或多个元素,返回数组长度
    Array.prototype.myUnshift = function (...value) {
   
            for (var i = (this.length + arguments.length - 1); i > arguments.length - 1; i--) {
   
                this[i] = this[i - arguments.length]
            }
            for (var k = 0; k < arguments.length; k++) {
   
                this[k] = arguments[k]
            }
            return this.length
        }
5:reverse():颠倒数组中元素顺序
   Array.prototype.myReverse = function(){
   
            for(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值