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

元气小坏坏 提交于 2020-04-06 07:35:19

问题


According to the Mozilla Developer Website:

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.

I have also tried npm install n -g


回答1:


It seems that flatMap is not supported on your browser. Here you are a complete list of supported browsers: 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

By the way, it is useful when applied on a multidimensional array!




回答2:


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). CanIUse table here.

Also note that it is used primarily for multidimensional arrays (to avoid chaining map and flat, hence flatMap).



来源:https://stackoverflow.com/questions/55530690/javascript-flatmap-method-over-array-flatmap-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!