js源码-数组中的push()和unshift()方法的源码实现

人话不多,直接上代码,在代码中解析,不足之处请谅解:

push()

Array.prototype._push=function(...value){//在Array原型链上添加_push方法
    for(var i=0;i<arguments.length;i++){//按索引从小到大循环数组
        this[this.length]=arguments[i];//把入参,按照顺序,依次添加在数组的索引最大值加一的位置
    }
}
var arr=[231];//例子
arr._push(1,2,3,4);//调用原型链上的_push方法
console.log(arr);//结果:[231,1,2,3,4]
unshift()
Array.prototype._unshift=function(...value){ //在原型链上新增一个_unshift方法
// this.length+arguments.length-1:数组的最新的最大索引值
// 数组原有的元素需要整体完后挪动的最大临界索引值
    for(var i=this.length+arguments.length-1;i>arguments.length-1;i--){ 
        this[i]=this[i-arguments.length]; //此处把原有元素赋值给该元素在数组中新的索引地方
        // 第一个for循环就是把原有的元素往后挪,为参说挪出刚刚好的位置索引值
    }
    for(var k=0;k<arguments.length;k++){//入参只需要正常for循环
        this[k]=arguments[k];//数组从0开始往上按顺序添加入参元素
        // 第二个for循环其实就是把入参,按顺序在数组头部插入
    }
    return this.length;//最终返回新数组的长度
}
var item1=[2,3,4];//例子
let currentLength=item1._unshift(1,2222,22222,99999);//自定义插入参数
console.log(item1,currentLength);//打印结果:[1, 2222, 22222, 99999, 2, 3, 4] 7

由于时间文,本次就分享两个方法,后续会陆续推出更多源码案例以及实现;

原文地址:https://www.cnblogs.com/nimon-hugo/p/14501376.html