本文主要是介绍自己实现数组的push方法和unshift方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
思路都用到了函数的agruments参数
实现push
let arr = [9,8,7];// 自定义pushArray.prototype.customPush = function (){for(let i = 0; i < arguments.length; i++){this[this.length] = arguments[i];}return this.length;}arr.push(1,2);console.log(arr1);//[9, 8, 7, 1, 2]
实现unshift
因为unshift是在数组的前面添加所以用到了splice在下标为0的位置删除0个元素,再添加一个元素
let arr = [1,2, 3]// 自定义unshiftArray.prototype.customUnshift = function(){for(let i = 0; i < arguments.length; i++){this.splice(0, 0, arguments[i])}}arr.customUnshift(4,5)console.log(arr)//[5, 4, 1, 2, 3]
这篇关于自己实现数组的push方法和unshift方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!