重构
- shift
// 重构
Array.prototype.myShift = function () {
// 拿到数组第一个数
var num = this[0];
// 将数组的第二项赋值给第一项,第三项赋值给第二项...
// this[0] = this[1];
// this[1] = this[2];
// this[2] = this[3];
for(var i = 0;i<this.length;i++){
this[i] = this[i+1];
}
// 通过length属性删除最后一项
this.length = this.length-1;
return num;
};
var arr = [1,2,3,4];
var result = arr.myShift();
console.log(arr);
console.log(result);
- unshift
// 重构
Array.prototype.myUnshift = function () {
// 插入数之后的长度 = 原数组的长度 + 插入数的长度
var len = this.length + arguments.length;
// 将这个长度给了数组之后,数组会多出来相应的空槽
this.length = len;
// 将原数组中的数向后移动
/*this[5] = this[3];
this[4] = this[2];
this[3] = this[1];
this[2] = this[0];
this[0] = arguments[0];
this[1] = arguments[1];*/
for(var i=this.length-1;i>=arguments.length;i--){
// this[this.length-1] = this[this.length-arguments.length-1]
this[i] = this[i-arguments.length];
}
// 将需要插入的值赋值给数组前面
for(var j=0;j<arguments.length;j++){
this[j] = arguments[j];
}
return len;
};
var arr = [1,2,3,4];
var result = arr.myUnshift(99,88,5,6,7,8);
console.log(arr);
console.log(result);