flatMap()
方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 和 深度值1的 flat 几乎相同,但 flatMap
通常在合并成一种方法的效率稍微高一些。
{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}
此交互式示例的源代码存储在GitHub存储库中。如果您想要为交互式示例项目做出贡献,请复制https://github.com/mdn/interactive-examples,并向我们发送 pull request。
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
// 返回新数组的元素
}[, thisArg])
callback
currentValue
index
可选array
可选map
数组thisArg
可选callback
函数时 使用的this
值。 一个新的数组,其中每个元素都是回调函数的结果,并且结构深度 depth
值为1。
有关回调函数的详细描述,请参见 Array.prototype.map()
。 flatMap
方法与 map
方法和深度depth为1的 flat
几乎相同.
Map
与 flatMap
var arr1 = x => [x * 2]
// [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]
// 只会将 flatMap 中的函数返回的数组 “压平” 一层
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]
虽然上面的代码使用 map 和 flatMap 好像都可以,但这只能展示如何使用 flatMap。
所以,为了更好的展示 flatMap 的作用,下面我们将包含几句话的数组拆分成单个汉字组成的新数组。
let arr = ["今天天气不错", "", "早上好"]
arr.map(s => s.split(""))
// [["今", "天", "天", "气", "不", "错"],[""],["早", "上", "好"]]
arr.flatMap(s => s.split(''));
// ["今", "天", "天", "气", "不", "错", "", "早", "上", "好"]
reduce
) 与 合并(concat
)var arr1 = [1, 2, 3, 4];
arr1.flatMap(x => [x * 2]);
// 等价于
arr1.reduce((acc, x) => acc.concat([x * 2]), []);
// [2, 4, 6, 8]
规范 | 状态 | 备注 |
---|---|---|
Array.prototype.flatMap proposal |
Draft |
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flatMap | Chrome Full support 69 | Edge No support No | Firefox Full support 62 | IE No support No | Opera Full support 56 | Safari Full support 12 | WebView Android Full support 69 | Chrome Android Full support 69 | Edge Mobile No support No | Firefox Android Full support 62 | Opera Android Full support 56 | Safari iOS Full support 12 | Samsung Internet Android No support No | nodejs Full support 11.0.0 |