ECMAScript之flatMap()

The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

flatMap的方法主要就是将一个数组每个元素通过某个回调函数变成另外一个新的数组,并且这个新的数组层级会减少一个。

const arr1 = [1, 2, 1];

const result = arr1.flatMap((num) => (num === 2 ? [2, 2] : 1));

console.log(result);
// Expected output: Array [1, 2, 2, 1]

 其与map的区别如下:

const arr1 = [1, 2, 3, 4];

arr1.map((x) => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap((x) => [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap((x) => [[x * 2]]);
// [[2], [4], [6], [8]]
const arr1 = ["it's Sunny in", "", "California"];

arr1.map((x) => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap((x) => x.split(" "));
// ["it's","Sunny","in", "", "California"]

 

使用这个函数经常出现的一个错误是:

flatMap() is not a function.

 出现上述问题主要是由于node版本的问题,有些node的版本中没有flatMap函数。解决上述问题,我们可以通过安装core-js来解决,core-js是一个提供js函数各种实现的库。只需要引入对应的函数即可,比如此处的flatMap函数,可以引入如下即可:

import 'core-js/fn/array/flat-map'

其他的函数,可以参考core-js的GitHub:GitHub - zloirock/core-js: Standard Library

core-js分为core-js2和core-js3的区别。

你可能感兴趣的:(JavaScript,ecmascript,前端,开发语言)