JS处理数组方法重写(二)

150 阅读1分钟

我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情

[JS数组方法重写(一)](JS处理数组方法重写 - 掘金 (juejin.cn))

push方法

向数组尾部添加元素。 注意在调用push方法时,会返回数组添加元素后的长度。 且push里面可以传递不止一个参数。

Array.prototype.my_push=function(...arr){
    for(let i=0;i<arr.length;i++){
        this[this.length]=arr[i]
    }
    return this.length
}

const arr1=[2,3,4,]
console.log(arr1.my_push(5,6,7));// 6
console.log(arr1);//[ 2, 3, 4, 5, 6, 7 ]

pop方法

从数组尾部删除一个元素。 注意在调用pop时返回被删除的元素。

Array.prototype.my_pop=function(){
    // 记录数组尾部的元素
    const tagItem=this[this.length-1]
    
    // 数组长度减一,直接去掉最尾部的元素
    this.length--
    
    // 将被删除的元素返回
    return tagItem
}
const arr1=[4,5,6]
console.log(arr1.my_pop());// 6
console.log(arr1);// 4,5

unshift方法

从数组头部添加元素,并返回添加后的数组长度。

Array.prototype.my_unshift=function(...arr){
    // 从0开始,删除0个,添加...arr
    this.splice(0,0,...arr)
    return this.length
}

但是这样写有点偷鸡。。。 正常如下:

Array.prototype.my_unshift=function(...arr){
    this.length+=arr.length
    for(let i=this.length-1;i>0;i--){
        this[i]=this[i-arr.length]
    }
    for(let i=0;i<arr.length;i++){
        this[i]=arr[i]
    }
    return this.length
}

思路:先让数组整体后移要添加的元素个数的长度,之后把要添加的元素添加到数组头部

shift方法

从数组头部删除一个元素,返回被删除的元素。

Array.prototype.my_shift=function(){
    const tagItem=this[0]
    for(let i=0;i<this.length;i++){
        this[i]=this[i+1]
    }
    this.length--
    return tagItem
}
const arr1=[2,4,5]
console.log(arr1.my_shift()); // 2
console.log(arr1); // [ 4, 5 ]

思路:数组整体前移一个位置,之后删掉最后一个位置的元素。

reverse方法

Array.prototype.my_reverse=function(){
    let temp
    
    //这里使用Math.floor向下取整,防止数组元素个数为奇数时会循环中间数
    for(let i=0;i<Math.floor(this.length/2);i++){
        temp=this[i]
        this[i]=this[this.length-i-1]
        this[this.length-i-1]=temp
    }
    return this
}
const arr1=[2,3,4]
console.log(arr1.my_reverse());// [ 4, 3, 2 ]
const arr2=[2,3,4,5,6,7,8,9]
console.log(arr2.my_reverse());// [9, 8, 7, 6, 5, 4, 3, 2]

思路:对称交换两个元素的位置。