繁体   English   中英

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

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

根据 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.

例子:

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

为什么这会返回此错误?

编辑

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

我也试过npm install n -g

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

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

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

您的浏览器似乎不支持flatMap 这是支持的浏览器的完整列表: https : //caniuse.com/#search=flatMap

如果你真的想使用它,这里你是一个 polyfill,它将支持向下到 ES3: https : //www.npmjs.com/package/array.prototype.flatmap

顺便说一句,当应用于多维数组时它很有用!

这意味着您使用的网络浏览器或其他开发环境不支持Array.prototype.flatMap (目前 Edge 和 IE 不支持)。 CanIUse 表在这里

另请注意,它主要用于多维数组(以避免链接mapflat ,因此flatMap )。

暂无
暂无

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

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