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

你可能感兴趣的文章
Nginx配置参数中文说明
查看>>
Nio ByteBuffer组件读写指针切换原理与常用方法
查看>>
NIO Selector实现原理
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
node.js 怎么新建一个站点端口
查看>>
Node.js 文件系统的各种用法和常见场景
查看>>