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

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

Array.prototype.flat

Array.prototype.flat 是 JavaScript 数组方法,用于对数组进行扁平化处理。它会根据指定的深度递归遍历数组,将所有元素与子数组中的元素合并成一个新数组返回。

工作原理

  • depth 参数:指定要提取的嵌套数组的结构深度,默认值为 1,表示展开一层。
    • 例如:arr.flat(2) 会展开两层嵌套数组。
    • 如果传入 Infinity,则会展开任意深度的嵌套数组。
  • 特殊情况:传入 0 或负值时,不会展开数组,直接返回浅拷贝。

示例

let arr = [1, 2, [3, 4, [5, 6]]];// 只展开一层arr.flat(); // [1, 2, 3, 4, [5, 6]]arr.flat(2); // [1, 2, 3, 4, 5, 6]// 展开任意深度arr.flat(Infinity); // [1, 2, 3, 4, 5, 6]

Array.prototype.flatMap

Array.prototype.flatMap 方法结合了 mapflat,首先对数组中的每个元素应用 map 函数,然后再对结果数组进行扁平化处理。

语法

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

示例

let arr = [1, 2, 3, 4];// 基本使用let arr1 = arr.flatMap(x => [x * 2]); // [2, 4, 6, 8]// 与传统方法对比let arr2 = arr.map(x => [x * 2]); // [[2], [4], [6], [8]]arr2.flat(); // [2, 4, 6, 8]

注意事项

  • flatMap 的执行顺序是先 mapflat,与传统的 mapflat 组合不同。
  • 示例 [1, 2, [3], 4].flatMap(x => x + 1) 的结果为 [2, 3, "31", 5],因为数组与数字相加时会自动调用 toString() 方法。

实现方法

Array.prototype.flatMap = function(mapper) {  return this.map(mapper).flat();}

总结

  • flat 方法适用于需要展开一定深度的嵌套数组。
  • flatMap 方法适用于先映射后展开数组的场景,常用于将嵌套数组转换为扁平化的结果数组。

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

你可能感兴趣的文章
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>
NPOI初级教程
查看>>
NPOI利用多任务模式分批写入多个Excel
查看>>
NPOI在Excel中插入图片
查看>>
NPOI将某个程序段耗时插入Excel
查看>>
NPOI格式设置
查看>>
NPOI设置单元格格式
查看>>