Js数组方法重构

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' ]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值