array.flatmap()是javascript中的内置函数,用于将输入数组元素展平为新数组。该方法首先利用映射函数映射每个元素,然后将输入数组元素展平为一个新数组。下面我们就来看flatmap()的具体使用方法。
flatmap()的基本语法为:
var a = array.flatmap(function callback(current_value, index, array)){ //返回的新数组元素}
callback:这是在三个参数的帮助下为新数组生成元素的函数,如下所示:
current_value:它是输入数组元素。
index:这是可选的。它是input元素的索引。
array:这是可选的。它在调用数组映射时使用。
下面我们来看两个具体示例
例1:
代码如下
<script> var a = [ 1, 2, 3, 4, 5 ]; b = a.map(x => [x * 3]); document.write(b); c = arr1.flatmap(x => [x * 3]); document.write(c); d = arr1.flatmap(x => [[ x * 3 ]]); document.write(d); </script>
输出结果为:
[[3],[6],[9],[12],[15]] [3,6,9,12,15] [[3],[6],[9],[12],[ 15]
例2:
代码如下
<script> var a = [ 1, 2, 3, 4, 5 ]; array.flatmap(x => [x * 3]); b = a.reduce((acc, x) => acc.concat([ x * 3 ]), []); document.write(b); </script>
输出结果为:[3,6,9,12,15]
本篇文章到这里就已经全部结束了,更多精彩内容大家可以关注的其他相关栏目教程!!!
以上就是flatmap函数怎么使用的详细内容。