- 写一个myPop,实现同pop()相同的功能
var arr = ['test','hello','ronda','tom','briup'];
console.log('原数组:',arr);
Array.prototype.myPop = function(){
var temp = this[this.length-1];
this.length--;
return temp;
}
var result = arr.myPop();
console.log(result);
console.log(arr);
- 写一个myShift,实现同shift()相同的功能
var arr = ['test','hello','ronda','tom','briup'];
console.log('原数组:',arr);
Array.prototype.myShift = function(){
var temp = this[0]
for(var i=0;i<this.length-1;i++){
this[i] = this[i+1]
}
this.length--
return temp
}
console.log(arr.myShift())
console.log(arr)
- 写一个myPush,实现同push()相同的功能
var arr = ['test','hello','ronda','tom','briup'];
console.log('原数组:',arr);
Array.prototype.myPush = function(){
for(var i=0;i<arguments.length;i++){
this[this.length] = arguments[i]
}
return this.length
}
console.log(arr.myPush(null,2,'2','aaa',[1,2]))
console.log(arr)
- 写一个myUnshift,实现同unshift()相同的功能
var arr = ['test','hello','ronda','tom','briup'];
console.log('原数组:',arr);
Array.prototype.myUnshift = function(){
this.length += arguments.length
var j = this.length - 1 - arguments.length
for(var i=this.length-1;i>=arguments.length;i--){
this[i] = this[j]
j--
}
var m=0;
for(var k=0;k<arguments.length;k++){
this[m] = arguments[k]
m++
}
return this.length
}
console.log(arr.myUnshift(null,3,[1,1]))
console.log(arr)
- 写一个myReverse,实现同reverse()相同的功能
var arr = ['test','hello','ronda','tom','briup'];
console.log('原数组:',arr);
Array.prototype.myReverse = function(){
for(var i=0;i<this.length/2;i++){
var temp = this[i];
this[i] = this[this.length-1-i];
this[this.length-1-i] = temp;
}
return this;
}
console.log(arr.myReverse())
console.log(arr)