CS-Interview-Knowledge-Map icon indicating copy to clipboard operation
CS-Interview-Knowledge-Map copied to clipboard

flatMap 的示例有误

Open zhuweiyou opened this issue 5 years ago • 1 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]

zhuweiyou avatar Sep 28 '18 15:09 zhuweiyou

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

TENCHIANG avatar Dec 15 '20 14:12 TENCHIANG

这是来自QQ邮箱的假期自动回复邮件。   您好,我最近正在休假中,无法亲自回复您的邮件。我将在假期结束后,尽快给您回复。

imondo avatar Jun 27 '23 03:06 imondo