简体   繁体   English

Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数)

[英]Javascript - flatMap method over array - (flatMap is not a function)

According to the Mozilla Developer Website:根据 Mozilla 开发者网站:

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map followed by a flat of depth 1, but flatMap is often quite useful, as merging both into one method is slightly more efficient.

Example:例子:

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() is not a function

Why is this returning this error?为什么这会返回此错误?

EDIT编辑

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.我正在通过 Atom 文本编辑器运行它,并使用 HomeBrew 使用brew upgrade node将其更新到最新版本,但它仍然给我同样的错误。

I have also tried npm install n -g我也试过npm install n -g

I was getting this when testing with jest, it's because flatmap is only part of node 11 and I was using node 10.我在用 jest 测试时得到了这个,这是因为flatmap只是节点 11 的一部分,而我使用的是节点 10。

As a workaround, I added require('core-js/stable');作为一种解决方法,我添加了require('core-js/stable'); in my setupTests.ts .在我的setupTests.ts

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.因此,我还会将该 require 行放在我的应用程序导入中的某处。

It seems that flatMap is not supported on your browser.您的浏览器似乎不支持flatMap Here you are a complete list of supported browsers: https://caniuse.com/#search=flatMap这是支持的浏览器的完整列表: https : //caniuse.com/#search=flatMap

If you really want to use it, here you are a polyfill that will grant support down to ES3: https://www.npmjs.com/package/array.prototype.flatmap如果你真的想使用它,这里你是一个 polyfill,它将支持向下到 ES3: https : //www.npmjs.com/package/array.prototype.flatmap

By the way, it is useful when applied on a multidimensional array!顺便说一句,当应用于多维数组时它很有用!

It means you're using a web browser or other development environment that does not support Array.prototype.flatMap (currently Edge and IE have no support).这意味着您使用的网络浏览器或其他开发环境不支持Array.prototype.flatMap (目前 Edge 和 IE 不支持)。 CanIUse table here . CanIUse 表在这里

Also note that it is used primarily for multidimensional arrays (to avoid chaining map and flat , hence flatMap ).另请注意,它主要用于多维数组(以避免链接mapflat ,因此flatMap )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM