JS(ES5) 实现数组方法(pop、push、shift、unshift、forEach)的重构

1.重构方法之 push()方法

var arr = [1, 322, 44, 'wo'];
Array.prototype.myPush = function () {
    for (var i = 0; i < arguments.length; i++) {
        this[this.length] = arguments[i];
    }
    return this.length;
}
console.log(arr.myPush(2, 233)); // 6
console.log(arr);   //[ 1, 322, 44, 'wo', 2, 233 ]

2.重构方法之 pop()方法

var arr = [1, 322, 44, 'wo'];
Array.prototype.myPop = function () {
    if (this.length == 0) {
         return undefined;
    }
    var lastElement = this[this.length - 1];
    this.length = this.length - 1;
    return lastElement;
}
console.log(arr.myPop()); // wo
console.log(arr);    // [ 1, 322, 44 ]

3.重构方法之 shift()方法

var arr = [1, 322, 44, 'wo'];
Array.prototype.myShift = function () {
    if (this.length == 0) {
        return undefined;
    }
    var firstElement = this[0];
    for (var i = 0; i < this.length - 1; i++) {
        this[i] = this[i + 1];
    }
    this.length = this.length - 1;
    return firstElement;
}
console.log(arr.myShift()); // 1
console.log(arr); // [ 322, 44, 'wo' ]

4.重构方法之 unshift()方法

var arr = [1, 322, 44, 'wo'];
Array.prototype.myUnshift = function () {
    var len = this.length + arguments.length;
    for (var i = len - 1; i >= 0; i--) {
        //原数组当前的下标 > 参数数组长度-1  就进行数组的前进
        if (i > arguments.length - 1) {
            this[i] = this[i - arguments.length];
        } else {  //把参数数组插入到原数组
            this[i] = arguments[i];
        }
    }
    return this.length;
}
console.log(arr.myUnshift(22, "aa")); //6
console.log(arr); // [ 22, 'aa', 1, 322, 44, 'wo' ]

5.重构方法之 forEach()方法

var arr = [1, 322, 44, 'wo'];
Array.prototype.myForEach = function (fun) {
    for (var i = 0; i < this.length; i++) {
        fun(this[i], i, this);
    }
}
arr.myForEach((item, index, arr) => {
    console.log(item, index, arr);
})

//运行结果:
// 1 0 [ 1, 322, 44, 'wo' ]
// 322 1 [ 1, 322, 44, 'wo' ]
// 44 2 [ 1, 322, 44, 'wo' ]
// wo 3 [ 1, 322, 44, 'wo' ]

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值