博客
关于我
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/

你可能感兴趣的文章
node安装及配置之windows版
查看>>
Node实现小爬虫
查看>>
Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
查看>>
Node提示:npm does not support Node.js v12.16.3
查看>>
Node搭建静态资源服务器时后缀名与响应头映射关系的Json文件
查看>>
Node服务在断开SSH后停止运行解决方案(创建守护进程)
查看>>
node模块化
查看>>
node模块的本质
查看>>
node环境下使用import引入外部文件出错
查看>>
node环境:Error listen EADDRINUSE :::3000
查看>>
Node的Web应用框架Express的简介与搭建HelloWorld
查看>>
Node第一天
查看>>
node编译程序内存溢出
查看>>
Node读取并输出txt文件内容
查看>>
node防xss攻击插件
查看>>
noi 1996 登山
查看>>
noi 7827 质数的和与积
查看>>
NOI-1.3-11-计算浮点数相除的余数
查看>>
NOI2010 海拔(平面图最大流)
查看>>
NOIp2005 过河
查看>>