(十七)map、flatMap和reduce方法的补充

关于reduce方法

语法array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total为之前的之和;initialValue可以控制其第一个值;例如:

关于map方法

语法array.map(function(currentValue,index,arr), thisValue)
map方法返回的值是一个数组(返回的新数组与原数组没有任何引用关系);该数组的每个值是由每次item遍历返回值组成

注意map的例子:
['1','2','3'].map(parseInt)
//结果是[1,NaN,NaN];注意map有三个参数:索引元素,索引以及原数组
//  parseInt('1', 0) -> 1
//  parseInt('2', 1) -> NaN
//  parseInt('3', 2) -> NaN
关于FlatMap

FlatMap方法和map方法是类似的;只是相较于map方法而言,FlatMap方法可以将二维数组降维,但是也只限于二维数组的降维

[1, [2], 3].flatMap((v) => v + 1)
// -> [2, 3, 4]
多维数组的彻底降维
const flattenDeep = (arr) => Array.isArray(arr)
  ? arr.reduce( (a, b) => [...a, ...flattenDeep(b)] , [])
  : [arr]

flattenDeep([1, [[2], [3, [4]], 5]])

原文地址:https://www.cnblogs.com/smileyqp/p/12675320.html