最近在面试,有一些是需要自己实现一些方法的,闲的没事就写一下记录
const arr = [1, 2, 3];
// 将方法挂载到原型上,方法要用function来写,不能使用箭头函数,因为箭头函数没有arguments且this指向指向window而不能获取到对象本身
Array.prototype.myUnshift = function () {
const argsLen = arguments.length;
for (let i = argsLen - 1; i >= 0; i--) {
// 插入
this.splice(0, 0, arguments[i]);
}
return arr;
};
console.log(arr.myUnshift(4, 5, 6));//[4,5,6,1,2,3]