InterviewMap/CS-Interview-Knowledge-Map

flatMap 的示例有误

zhuweiyou opened this issue · 2 comments

https://github.com/InterviewMap/CS-Interview-Knowledge-Map/blob/master/JS/JS-en.md#mapflatmap-and-reduce

[1, [2], 3].flatMap((v) => v + 1)
// -> [2, 3, 4]

上面这个,运行结果是不正确的,而且没有表达 flatMap 的作用
应该是类似这样

const arr = [1, 2, 3, 4]
arr.map(x => [x * 2])
// [[2], [4], [6], [8]]

arr.flatMap(x => [x * 2])
// [2, 4, 6, 8]

对,其实要使用 [1, [2], 3].flatMap(v => v).map(v => v + 1) 就对了
flatMap 的回调函数,参数分别是 element, index, array,所以在 flatMap 时,还是会碰到数组的
flatMap 之后,数组才会降一层维度