这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
flatMap()方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 和 深度值1的 flat 几乎相同,但flatMap通常在合并成一种方法的效率稍微高一些。
{{EmbedInteractiveExample("pages/js/array-flatmap.html")}}
此交互式示例的源代码存储在GitHub存储库中。如果您想要为交互式示例项目做出贡献,请复制https://github.com/mdn/interactive-examples,并向我们发送一个拉请求。
语法
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]
规范
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flatMap proposal |
Draft |
浏览器兼容性
此页面中的兼容性表是由结构化数据生成的。如果您想提供数据,请查看https://github.com/mdn/Browser-compat-data,并向我们发送拉请求。
Update compatibility data on GitHub
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic support | 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 No support No |
Legend
- Full support
- Full support
- No support
- No support
- Experimental. Expect behavior to change in the future.
- Experimental. Expect behavior to change in the future.