这个 大堆flatMap() 是JavaScript中的一个内置函数,用于将输入数组元素展平为新数组。 该方法首先利用映射函数映射每个元素,然后将输入的数组元素展平为一个新的数组。 语法:
null
var A = array.flatMap(function callback(current_value, index, Array)){ // It returns the new array's elements.}
参数:
- 当前_值: 它是输入数组元素。
- 索引:
- 这是可选的。
- 它是输入元素的索引。
- 数组:
- 这是可选的。
- 它在调用数组映射时使用。
返回值: 它返回一个新数组,其元素是回调函数的返回值。 显示上述函数功能的JavaScript代码: 代码#1:
javascript
<script> // Taking input as an array A having some elements. var A = [ 1, 2, 3, 4, 5 ]; // Mapping with map function. b = A.map(x => [x * 3]); document.write(b); // Mapping and flatting with flatMap() function. c = arr1.flatMap(x => [x * 3]); document.write(c); // Mapping and flatting with flatMap() function. 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: 这种压平也可以在reduce和concat的帮助下完成。
javascript
<script> // Taking input as an array A having some elements. var A = [ 1, 2, 3, 4, 5 ]; array.flatMap(x => [x * 3]); // is equivalent to b = A.reduce((acc, x) => acc.concat([ x * 3 ]), []); document.write(b); </script> |
输出:
[3, 6, 9, 12, 15]
支持的浏览器:
- 谷歌Chrome 69及以上
- 边缘79及以上
- Firefox 62及以上版本
- 56岁及以上
- Safari 12及以上
注: 此功能仅在Firefox中每晚可用。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END