博客
关于我
ES2019 中的 Array.prototype.flat 和 Array.prototype.flatMap
阅读量:338 次
发布时间:2019-03-04

本文共 1415 字,大约阅读时间需要 4 分钟。

Array.prototype.flat

Array.prototype.flat 是数组扁平化方法,按照一个指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回

let newArray = arr.flat([depth])

depth 参数指定要提取嵌套数组的结构深度,默认值为 1 ,即展开一层;若要展开两层,可以传 2 ;如需要展开任意深度的嵌套数组,可以使用 Infinity

let arr = [1, 2, [3, 4, [5, 6]]];// 不传或者传1都只展开一层arr.flat(); // [1, 2, 3, 4, [5, 6]]arr.flat(1); // [1, 2, 3, 4, [5, 6]]// 展开指定深度arr.flat(2); // [1, 2, 3, 4, 5, 6]// 传入0或者负值不进行展开,只是浅拷贝arr.flat(0); // [1, 2, [3, 4, [5, 6]]]let arr2 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];// 展开任意深度arr2.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Infinity 跟 NaN 一样也是属于 number 类型

Array.prototype.flatMap

Array.prototype.flatMap 方法首先使用 map 函数映射数组的每个元素,然后再为每个元素调用一下 flat 函数,相当于先 mapflat

var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {

// return element for new_array
}[, thisArg])

let arr = [1, 2, 3, 4];// 使用 flatMaplet arr1 = arr.flatMap(x => [x * 2]); // [2, 4, 6, 8]// 相当于调用 map 后调用 flatlet arr1 = arr.map(x => [x * 2]); // [[2], [4], [6], [8]]arr2 = arr1.forEach(x => x.flat()); // [2, 4, 6, 8]

注意一下,很多人看到 flatMap ,以为是先 flatmap ,但事实上是先 mapflat ,我们可以测试一下:

[1, 2, [3], 4].flatMap(x => x + 1);// [2, 3, "31", 5]

很明显,flatMap 是先执行了 map ,中间那个 "31" 是因为数组与数字相加时,数组自动调用了 toString() 方法。

根据上面的分析,我们可以简单实现一下 faltMap 方法:

Array.prototype.flatMap = function(mapper) {   	return this.map(mapper).flat();}// flat 方法可以这样实现const flat = (arr) => arr.reduce((a, b) => a.concat(b), []);

参考:

转载地址:http://ptye.baihongyu.com/

你可能感兴趣的文章
ndk-cmake
查看>>
NdkBootPicker 使用与安装指南
查看>>
ndk特定版本下载
查看>>
NDK编译错误expected specifier-qualifier-list before...
查看>>
Neat Stuff to Do in List Controls Using Custom Draw
查看>>
Necurs僵尸网络攻击美国金融机构 利用Trickbot银行木马窃取账户信息和欺诈
查看>>
Needle in a haystack: efficient storage of billions of photos 【转】
查看>>
NeHe OpenGL教程 07 纹理过滤、应用光照
查看>>
NeHe OpenGL教程 第四十四课:3D光晕
查看>>
Neighbor2Neighbor 开源项目教程
查看>>
neo4j图形数据库Java应用
查看>>
Neo4j图数据库_web页面关闭登录实现免登陆访问_常用的cypher语句_删除_查询_创建关系图谱---Neo4j图数据库工作笔记0013
查看>>
Neo4j图数据库的介绍_图数据库结构_节点_关系_属性_数据---Neo4j图数据库工作笔记0001
查看>>
Neo4j图数据库的数据模型_包括节点_属性_数据_关系---Neo4j图数据库工作笔记0002
查看>>
Neo4j安装部署及使用
查看>>
Neo4j电影关系图Cypher
查看>>
Neo4j的安装与使用
查看>>
Neo4j(1):图数据库Neo4j介绍
查看>>
Neo4j(2):环境搭建
查看>>
Neo4j(3):Neo4j Desktop安装
查看>>