javascript higher-order functions---filter---map---reduce

javascript higher-order functions—filter—map—reduce

A higher-order function means that the parameter passed to the function is a function, for example

filter(function(){.....})

Here is an example of array

  1. Filter usage
    The Chinese meaning of filter is the meaning of filtering, in the array is to filter out the data that does not meet the conditions. The filtered array elements are stored in the new array.
    example:
 <script>
    let arr_1=[10,12,34,56,100,120,222];
    let arr_2=arr_1.filter(function(item){
    
    
      return item<100;
    })
    console.log(arr_2);
  </script>

The return here is to return the value that meets the condition to the array.

  1. Map usage The
    map function is to perform related operations on the elements in the array.
    Example:
 <script>
    let arr_1=[10,12,34,56,100,120,222];
    let arr_2=arr_1.map(function(item){
    
    
      return item*2
    })
    console.log(arr_2);
  </script>
  1. Reduce usage
    reduce can pass in two parameters, one is a function, the other is the starting value.
    The parameters in the function also have two fun (previous, now), one is the previous value and the other is the current value. Speaking of this, you may not particularly understand, here is an example:
<script>
    let arr_1=[10,12,34,56,100,120,222];
    let arr_2=arr_1.reduce(function(previous,now){
    
    
      return previous+now;
    },0)
    console.log(arr_2);
  </script>

The final return value here is 554. It is to make the previous parameter the value of the second parameter, which is 0, and then execute previous+now, where now is traversed from the first one, and then the added value is assigned to previous to achieve this Cumulative effect.

Guess you like

Origin blog.csdn.net/weixin_47450807/article/details/109279393