博客
关于我
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.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>
Node.js 的事件循环(Event Loop)详解
查看>>
node.js 简易聊天室
查看>>
Node.js 线程你理解的可能是错的
查看>>
Node.js 调用微信公众号 API 添加自定义菜单报错的解决方法
查看>>
node.js 配置首页打开页面
查看>>
node.js+react写的一个登录注册 demo测试
查看>>
Node.js中环境变量process.env详解
查看>>
Node.js之async_hooks
查看>>
Node.js升级工具n
查看>>
Node.js卸载超详细步骤(附图文讲解)
查看>>
Node.js基于Express框架搭建一个简单的注册登录Web功能
查看>>
Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
查看>>
Node.js安装及环境配置之Windows篇
查看>>
Node.js安装和入门 - 2行代码让你能够启动一个Server
查看>>
node.js安装方法
查看>>
Node.js官网无法正常访问时安装NodeJS的方法
查看>>
Node.js的循环与异步问题
查看>>
Node.js高级编程:用Javascript构建可伸缩应用(1)1.1 介绍和安装-安装Node
查看>>