博客
关于我
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切换源淘宝源的两种方法
查看>>
npm前端包管理工具简介---npm工作笔记001
查看>>
npm升级以及使用淘宝npm镜像
查看>>
npm发布包--所遇到的问题
查看>>
npm发布自己的组件UI包(详细步骤,图文并茂)
查看>>
npm和yarn清理缓存命令
查看>>
npm和yarn的使用对比
查看>>
npm如何清空缓存并重新打包?
查看>>
npm学习(十一)之package-lock.json
查看>>
npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
查看>>
npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
查看>>
npm安装教程
查看>>
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>