push(),pop(),shift(),unshift(),sort(),reverse()
1.入栈push()
push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度
push() 内部可以插入多个值,在数组末尾添加新值
Array.prototype.myPush = function(item){
this[this.length] = item;
return this.length
}
var a = [1,2,3,4]
a.myPush(5)
console.log(a)
2.出栈pop()
pop() 方法可以将数组最后一位元素删除,
Array.prototype.myPop = function(){
var b=this.length;
var result = this[b-1];
this.length = b - 1;
return result;
}
var a = [1,2,3,4]
console.log(a.myPop())
console.log(a);
当数组为空时,打印undefined
var a = []
console.log(a.myPop())//undefined
console.log(a)//[]
3.出队shift()
shift() 方法可以将数组第一位元素删除
Array.prototype.myShift = function(){
var result = this[0]
for(var i=0;i<this.length-1;i++){
this[i] = this[i+1]
}
this.length = this.length-1
return result;
}
var a = [1,2,3,4]
a.myShift()
console.log(a)
4.入队unshift()
unshift() 方法可以在数组开头添加任意数量的元素
Array.prototype.myUnshift = function(item){
this.length = this.length+1
for(var i=this.length-1;i>=0;i--){
this[i]=this[i-1]
}
this[0]=item
return this.length
}
var a = [1,2,3,4]
a.myUnshift(100)
console.log(a)
5.sort()
sort() 方法用于对数组的元素进行排序
Array.prototype.sorts=function(){
for(var i=0;i<arr.length;i++){
var min = i;
for(var j=i+1;j<arr.length;j++){
if(arr[j]<arr[min]){
min = j
}
}
var temp = arr[i]
arr[i] = arr[min]
arr[min] = temp
}
return arr;
}
6.reverse()
reverse() 方法用于颠倒数组中元素的顺序
Array.prototype.newReverse= function(){
for(i=0,j=this.length-1;j>i;j--,i++){
var temp = this[i]
this[i] = this[j]
this[j] = temp
}
return this
}
var a = [1,2,3,4,5,6,7,8]
a.newReverse()
console.log(a)