JS高阶函数--------map、reduce、filter

一、filter

filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意: filter() 不会对空数组进行检测。

注意: filter() 不会改变原始数组。

1.语法

 
Array.filter(function(currentValue, indedx, arr), thisValue)

第一个参数是函数

这个回调函数的返回值是一个boolean值

当检查元素符合过滤条件的时候会返回true,函数内部会自动将这个元素加入新数组中

当不符合条件时会返回false,函数内部会过滤掉这个元素

例子1:返回数组中小于100的元素

const nums = [10, 20, 50, 101, 222,40]
  let newNums = nums.filter(function (n) {
    return n < 100
  })
  console.log(newNums); //[10, 20, 50, 40]

例子2筛选空格

const arr = ['0',1,2,3,4,"",5,1,4,'0',""];
  let arr_filter = arr.filter(function(x){
    return x;/* 筛选空格 */
  })
  console.log(arr_filter)

例子3:去除Array的重复元素

const arr_repeat = ['A', 'B', 'A', 'B', 'B', 'C', 'A', 'D', 'C']
  let arr_filter = arr_repeat.filter(function (el, index, self) {
//    console.log(self.indexOf(el))
//    console.log('index',index)
    return self.indexOf(el) == index

  })
console.log(arr_filter) //["A", "B", "C", "D"]

去除重复元素依靠的是indexOf总是返回某个元素第一次出现的位置,后续的重复元素位置index与indexOf返回的位置不相等,因此被filter滤掉了。

二、map

map() 方法:原数组中的每个元素调用一个指定方法后,返回返回值组成的新数组。

const nums = [2, 4, 6, 8, 10]
  newNums = nums.map(function (n) {
    return n*2
  })
  console.log(newNums)

三、reduce

reduce函数对数组中的所有内容进行汇总。

reduce()把一个函数作用在这个Array[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

语法

arr.reduce(callback,[initialValue])

第一个参数是回调函数

这个回调函数可以接收四个参数

previousValue (第一项的值或者上一次叠加的结果值,或者是提供的初始值(initialValue))
currentValue (数组中当前被处理的元素)
index (当前元素在数组中的索引)
array (数组本身)
initialValue (作为第一次调用 callback 的第一个参数,可以控制返回值的格式)不传默认为0

例子1:数组求和

    const arr = [1, 2, 3, 4, 5]
    let sum = arr.reduce(function (pre, cur) {
        console.log(pre, cur) //输出的是第一项的值或上一次叠加的结果,正在被处理的元素
        return pre + cur
    })
    console.log(sum) //15
1 2
3 3
6 4
10 5
15

例子2:不要使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数 

思路:1.先把字符串13579先变成Array——[1, 3, 5, 7, 9]
2.再利用reduce()就可以写出一个把字符串转换为Number的函数。

    const s = '13579'
    function string2int(s) {
        let arr = s.split('').map(function(x){
            return +x;
        })
        console.log(arr) //[1, 3, 5, 7, 9]
        let arr_reduce = arr.reduce(function(prev,res){
            console.log(prev, res)
            return prev*10+res;
        })
        console.log(arr_reduce) //13579
        return arr_reduce

    }
    string2int(s)

1.split() 方法用于把一个字符串分割成字符串数组。
格式:

stringObject.split(separator,howmany)

separator 必需。字符串或正则表达式,从该参数指定的地方分割 stringObject。如果是空字符串”,按每个单词分割
howmany 可选。该参数可指定返回的数组的最大长度。如果设置了该参数,返回的子串不会多于这个参数指定的数组。如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。
2.parsenInt和+

js提供了parseInt()和parseFloat()两个转换函数。前者把值转换成整数,后者把值转换成浮点数。

在字符串前面输入‘+’也能将字符转化成数值,输出如下:

 1 3
 13 5
 135 7
 1357 9
 13579

例子3:求一串字符串中每个字母出现的次数

暂时不会


参考:

https://www.cnblogs.com/jianxian/p/10582683.html

https://blog.csdn.net/baidu_36065997/article/details/79079880



猜你喜欢

转载自www.cnblogs.com/lyt0207/p/12066575.html