Use of array higher-order functions

1、filter(callbackfunction( ){ })

The callback function returns a boolean value, true: store the element in a new array, false: discard the element

 Example:

  data:[10, 20, 100, 140]

Requirement: Select the elements that are less than 100 and assign them to the new array dataNum:[]

Traditional way: Use a for loop to traverse the entire array, judge each element, and then perform the next step

Use filter to achieve:

 let dataNum = data.filter(function(n){
     
     return n < 100;
     
 })

ES6 arrow function writing:

 let dataNum = data.filter( n => { return n < 100 })

2、map(callbackfunction( ){ })

The callback function returns the result of the operation

Example:

  data:[10, 20, 100, 140]

Requirements: Multiply each element in the array by 2 to get the new result and store it in the new array dataNum:[]

Use map to achieve:

 let dataNum = data.map(function(n){
     
     return n*2;
     
 })

ES6 arrow function writing:

 let dataNum = data.map( n => { return n*2 })

to sum up:

The formal parameter n in the callback function of filter and map represents each element in the array

These two functions can pass in three parameters, but generally only two are used: item first, index second, array[] last

item: each item in the array

index: array subscript value

array[ ]: the new array

3、reduce(callbackfunction(prevVal, n){ }, 0)

Two parameters are generally passed in the callback function: prevVal and n

The callback function returns the result of performing the operation

prevVal: the previous/previous value, generally set to 0 and placed at the end of the function

n: current value

Example:

 let data = [10, 20, 100, 140]

Requirements: sum the elements in the array

Use reduce to achieve:

 let total = data.reduce( function( prev, n ){
 ​
     return n + prev;
     
 }, 0)

ES6 arrow function writing:

 let total = data.reduce( ( prev, n ) => {
 ​
     return n + prev;
     
 }, 0)

prev is not defined, so assign a value at the end, n represents each item in the array

The return statement has been executed data.length times, here is 4 times

The first time: return 10 + 0; the value of return becomes prev = 10

The second time: return 20 + 10; the value of return becomes prev = 30

The third time: return 100 + 30; the value of return becomes prev = 130

Fourth time: return 140 + 130; the value of return becomes prev = 270

There is no fifth time, to return the value of prev: 270

Guess you like

Origin blog.csdn.net/michaelxuzhi___/article/details/105753901