当前位置:网站首页>Advanced functions of ES6 operation array map (), filter (), reduce()

Advanced functions of ES6 operation array map (), filter (), reduce()

2022-06-30 15:05:00 Pan Gao

More , Please visit mine Personal blog .


arr.map() – Update the array

  1. The original array remains the same
  2. Callback function parameters :item( Array elements )、index( Sequence )、arr( Original array )
  3. Loop original array , Use return Operation output item , Return a new array , The new array has the same length as the original array
const originalArr = [1, 2, 3, 4, 5]

const newArr = originalArr.map((item, index, arr) => {
  return item * 2 //  Multiply each item of the original array by 2, Output new array , The original array remains the same 
})

console.info(newArr) // [2, 4, 6, 8, 10]

arr.filter() – Filter array

  1. The original array remains the same
  2. Callback function parameters :item( Array elements )、index( Sequence )、arr( Original array )
  3. Loop original array , Use return Determine whether to output elements , Return a new array , The length of the new array is less than or equal to the original array
const originalArr = [1, 2, 3, 4, 5]

const newArr = originalArr.filter((item, index, arr) => {
  return item % 2 == 0 //  Output the even items of the original array as a new array , The original array remains the same 
})

console.info(newArr) // [2, 4]

arr.reduce() – Overlay array

  1. The original array remains the same
  2. Callback function parameters :pre( The initial value is the first item of the array , This is followed by the return value of the last operation )、item( Array elements )、index( Sequence , Subscript from 1 Start )、arr( Original array )
  3. Loop original array , Use return Operation output , Until the end of the cycle , Returns an output value
const originalArr = [1, 2, 3, 4, 5]

const newArr = originalArr.reduce((pre, item, index, arr) => {
  //  First cycle :pre:1, item:2, index:1, pre+item:3
  //  The second cycle :pre:3, item:3, index:2, pre+item:6
  //  The third cycle :pre:6, item:4, index:3, pre+item:10
  //  The fourth cycle :pre:10, item:5, index:4, pre+item:15
  return pre + item
})

console.info(newArr) // 15

More programming teaching, please pay attention to the official account : Pangao will accompany you to learn programming

image


原网站

版权声明
本文为[Pan Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160508191866.html