push:向数组最后面添加值
重构方法:
Array.prototype.myPush=function(){
for(i=0;i<arguments.length;i++){
//遍历参数 并将参数添加到数组后面
this[this.length]=arguments[i]
}
//返回新数组长度
return this.length
}
var arr=[1,2,3,4,5]
console.log(arr);
var result=arr.myPush('hello','a','b')
//数组新长度
console.log(result);
console.log(arr);
运行结果:
[ 1, 2, 3, 4, 5 ]
8
[ 1, 2, 3, 4, 5, 'hello', 'a', 'b' ]
prop:删除数组最后的值
函数重构:
Array.prototype.myProp=function(){
// 获取数组最后一个值
var tem=this[this.length-1]
//数组长度减1
this.length--
return this.length
}
var arr=[1,2,3,4,'a']
console.log(arr);
var result=arr.myProp()
// 打印新数组长度
console.log(result);
console.log(arr);
运行结果:
[ 1, 2, 3, 4, 'a' ]
4
[ 1, 2, 3, 4 ]
shift:删除数组第一个值
函数重构:
Array.prototype.myShift=function(){
// 获取第一个参数
var tem=this[0]
// for循环将数组的值往前移一位
for(i=0;i<this.length;i++){
this[i]=this[i+1]
}
// 数组长度减1
this.length--
// 返回新数组长度
return this.length
}
arr=[1,2,3,4,'a']
console.log(arr);
var result=arr.myShift()
console.log(result);
console.log(arr);
运行结果:
[ 1, 2, 3, 4, 'a' ]
4
[ 2, 3, 4, 'a' ]
Unshift:将新项目添加到数组最前面
函数重构:
Array.prototype.myUnshift=function(){
// 新数组长度
var result=this.length+arguments.length
for(i=result;i>0;i--){
if(i>arguments.length)
{
// 原数组往后移
this[i-1]=this[i-1-arguments.length]
}else
{
// 新项目替换原数组的位置
this[i-1]=arguments[i-1]
}
}
return result
}
arr=[1,2,3,4,'a']
console.log(arr);
var result=arr.myUnshift('hello',8,9)
console.log(result);
console.log(arr);
运行结果:
[ 1, 2, 3, 4, 'a' ]
8
[ 'hello', 8, 9, 1, 2, 3, 4, 'a' ]
foreach:用于调用数组的每个元素,并将元素传递给回调函数。
函数重构:
Array.prototype.myForEach=function(fun){
for(i=0;i<this.length;i++){
// 遍历数组元素
fun(this[i],i,this)
}
}
var arr=[1,2,3,4,'a']
var result=arr.myForEach(function(item,index,arr){
// 输出数组元素和对应的下标,原数组
console.log(item,index,arr);
})
运行结果:
1 0 [ 1, 2, 3, 4, 'a' ]
2 1 [ 1, 2, 3, 4, 'a' ]
3 2 [ 1, 2, 3, 4, 'a' ]
4 3 [ 1, 2, 3, 4, 'a' ]
a 4 [ 1, 2, 3, 4, 'a' ]