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

mph*_*h85 17 javascript arrays node.js ecmascript-6 flatmap

根据 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);
Run Code Online (Sandbox Code Playgroud)

TypeError: arr.flatMap() is not a function

为什么这会返回此错误?

编辑

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

我也试过 npm install n -g

Mat*_*hew 21

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

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

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


Mic*_*iva 6

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

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

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