根据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
您的浏览器似乎不支持flatMap
。在这里,您是支持的浏览器的完整列表:https://caniuse.com/#search=flatMap
如果你真的想使用它,那么你就是一个polyfill,它将向ES3提供支持:https://www.npmjs.com/package/array.prototype.flatmap
顺便说一句,它应用于多维数组时很有用!
这意味着您正在使用不支持Array.prototype.flatMap
的Web浏览器或其他开发环境(目前Edge和IE不支持)。 CanIUse表here。
另请注意,它主要用于多维数组(以避免链接map
和flat
,因此flatMap
)。