Js数组map与forEach探究

forEach和map都是js数组的循环方法,都是循环数组,但是又有些许不同

相同点:

  1. 都是循环遍历数组中的每一项;
  2. 每次执行匿名函数都支持三个参数,参数分别为item(当前每一项),index(索引值),arr(原数组)
  3. 都不改变原始数组;

不同点:
forEach无返回值,map有返回值

他们都是js数组的方法,既然是是方法,那就必然有方法的三要素:方法名、参数和返回值
forEach的三要素分别是 forEach方法名、一个匿名函数作为参数,无返回值
map的 三要素是 map方法名,一个匿名函数作为参数,一个数组回值‘
因此forEach不能使用break来终止循环,因为在使用函数中是不能使用循环的

forEach实现原理应该类似如下

Array.prototype.ForEach=function (callback){
    for (let i = 0; i < this.length; i++) {
         callback(this[i],i,this)
    }
}

同理map

Array.prototype.Map=function (callback){
    let returnList=[];
    for (let i = 0; i < this.length; i++) {
        returnList.push(callback(this[i],i,this))
    }
    return returnList;
}

思路是在方法内部实现循环,通每循环执行一次匿名函数

基于此种思路可以实现类似删除数组中符合的一项

Array.prototype.Remove=function (prefunc){
    for (let i = 0; i <this.length ; i++) {
         let result=prefunc(this[i],i);
      //  if(result){
         if ( result && typeof (result)=="boolean"){
              this.splice(i,1);
              i--;
         }
    }
}

使用方法

let arr=[{name:"zhangsan",age:20},{name:"lisi",age:25},{name:"wanger",age:23}];
arr.Remove((item)=>{return item.age==20})
console.log(arr)

输出

[ { name: 'lisi', age: 25 }, { name: 'wanger', age: 23 } ]

同理实现类似Sort的功能

Array.prototype.Sort=function (prefunc){
    if (this.length==0){
        return this;
    }
    for (var i = 0; i < this.length - 1; i++) {
        for (var j = 0; j <this.length - i - 1; j++) {
            let sort=(prefunc && typeof(prefunc)=="function") ? prefunc(this[j],this[j+1])>0 :this[j]>this[j+1]
            if (sort){
                var temp = this[j];
                this[j] = this[j + 1];
                this[j + 1] = temp
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值