Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数) [英] Javascript - flatMap method over array - (flatMap is not a function)

查看:70
本文介绍了Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Mozilla 开发者网站:

According to the Mozilla Developer Website:

flatMap() 方法首先使用映射函数映射每个元素,然后将结果展平到一个新数组中.它与后跟深度为 1 的平面的地图相同,但 flatMap 通常非常有用,因为将两者合并为一种方法效率更高.

示例:

let arr = [1, 2, 4, 2, 3, 3, 4, 5, 5, 5, 8, 8, 9, 10];

const flatMap = arr.flatMap(x => x);
console.log(flatMap);

TypeError: arr.flatMap() 不是函数

为什么会返回此错误?

编辑

我通过 Atom 文本编辑器运行它,并使用 HomeBrew 使用 brew upgrade node 将其更新到最新版本,但它仍然给我同样的错误.

I am running this through Atom text editor and have used HomeBrew to update it to the latest version using brew upgrade node and it is still giving me the same error.

我也试过 npm install n -g

推荐答案

我在用 jest 测试时得到这个,这是因为 flatmap 只是 节点 11 的一部分,我使用的是节点 10.

I was getting this when testing with jest, it's because flatmap is only part of node 11 and I was using node 10.

作为一种解决方法,我在 setupTests.ts 中添加了 require('core-js/stable');.

As a workaround, I added require('core-js/stable'); in my setupTests.ts.

我想也有一些浏览器也没有这个.因此,我也会将该 require 行放在我的应用程序导入中的某处.

I presume also there are some browsers that won't have this either. As such I will also put that require line in my application imports somewhere.

这篇关于Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆