首页 > 其他分享 >4.使用reduce实现map,使用reduce实现filter

4.使用reduce实现map,使用reduce实现filter

时间:2023-03-05 09:11:06浏览次数:35  
标签:function map item reduce filter callback prev

前情提要: map函数接收一个函数作为参数,作为参数的函数接收三个参数值,分别是遍历数组的每一项元素,元素的索引和数组本身。这三个参数刚好和reduce函数接收的第一个函数参数的第2、3、4个参数是对应的。这是实现的核心 实现思路是,将每次遍历的元素,作为传入的函数的参数,并将函数执行的结果放入新的数组中。

使用reduce实现map

Array.prototype._map = function (callback) {
  if(typeof callback === 'function') {
    return this.reduce((prev,item,index,arr) => {
      prev.push(callback(item, index, arr))
      return prev
    }, [])
  } else {
    console.log(new Error('callback is not function'))
  }
}

let val = [1, 5, 6]._map(item => item+ 1)
console.log(val);  // [2, 6, 7]

使用reduce实现filter

  Array.prototype._filter = function (callback) {
    if(typeof callback === 'function') {
      return this.reduce((prev,item,index,arr) => {
        callback(item, index, arr) ? prev.push(item) : null
        return prev
      }, [])
    } else {
      console.log(new Error('callback is not function'))
    }
  }
  let val = [1, 5, 6]._filter(item => item > 2)
  console.log(val);  // [5, 6]

 

标签:function,map,item,reduce,filter,callback,prev
From: https://www.cnblogs.com/alwaysrun/p/17179787.html

相关文章

  • hook useRef,useState,父传子,useReducer,@observable,useCallback
    //返回一个可变的ref对象,该对象只有个current属性,初始值为传入的参数(id??'')。constactiveMenuKeyRef=useRef<string|number>(id??''); key[0]......
  • Set、可变参数、Collections工具类、Map集合
    一,set集合Collection集合的体系结构:List集合的见上个笔记,这个主要来学习Set和Map中的类1,Set集合的特点Set系列集合的特点:无序<添加和取出的顺序不一致>:不重复,无索......
  • /dev/mapper/control: open failed: Permission denied Failure to communicate with
    这个错误信息表明您在尝试访问/dev/mapper/control文件时遇到了权限问题。这通常意味着您需要以超级用户身份运行命令。您可以在命令前加上sudo来以超级用户身份运行命......
  • map运用
    map可以自动排序,第一个为最小值,返回最大值的时候时间复杂度为log(n)点击查看代码#include<bits/stdc++.h>usingnamespacestd;intmain(){ intn=10; map<int,in......
  • 调用Android原生@SystemApi、@Hide方法
      系统api.png如上图所示,PackageManager.getPermissionFlags()方法是被@SystemApi注解修饰过的方法,@SystemApi只允许systemapp调用或者用反射方法调用,反射方......
  • QMap
    QMap #include<QMap> PublicFunctions QMap() QMap(std::initializer_list<std::pair<Key,T>> list) QMap(constQMap<Key,T>&other) ......
  • 2023-03-03 js map 双重嵌套
    恩。。其实也没啥要记录的,记住关键一点就是必须要有return,不管是几重,比如:arr.map((item,index)=>{  return(    item.arr2.map((item2,index2)=>{......
  • springboot 过滤器FilterRegistrationBean详解
    一:基础知识1.通过FilterRegistrationBean实例注册,该方法能够设置过滤器之间的优先级2.为了演示优先级,这里创建2个测试过滤器类:Test1Filter、Test2Filter通过实现javax.serv......
  • Rethinking the Heatmap Regression for Bottom-up Human Pose Estimation
    本文的主要思想就是对heatmap图进行一个权重缩放。weight是作者提出的一个思路让模型将低输出值的位置加大权重,高输出值给予小权重,低输出值给与大全中。scaled_gt就是scale......
  • 10 个值得掌握的 reduce 技巧
    10个值得掌握的reduce技巧DevPoint深耕WEB开发10+年,拥有一颗工匠的心​关注他 2人赞同了该文章​展开目录 作为一个......