更灵活的 Map :array.flatMap()


map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。

const array1 = [1, 4, 9, 16];  
  
// pass a function to map  
const map1 = array1.map(x => x * 2);  
  
console.log(map1);  
// expected output: Array [2, 8, 18, 32]  

但有时,我们需要跳过数组中的某些元素,以上面的例子为例,当我们需要跳过元素 1 时,可以结合 filter 方法:

const array1 = [1, 4, 9, 16];  
  
// pass a function to map  
const map1 = array1  
    .filter(x => x !== 1)  
    .map(x => x * 2);  
  
console.log(map1);  
// expected output: Array [8, 18, 32]  

使用 map 和 filter 结合的方式固然可以解决我们的需求,但多个方法的结合让代码看起来不那么简洁易读,有没有更简短的方式来实现呢?

答案是肯定的。使用 flatMap 方法,flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为 1
的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。

const array1 = [1, 4, 9, 16];  
  
// pass a function to map  
const map1 = array1.flatMap(x => x === 1? [] :[ x*2 ])  
  
console.log(map1);  
// expected output: Array [8, 18, 32]  

flatMap
能用于在map期间增删项目(也就是修改items的数量)。换句话说,它允许你遍历很多项使之成为另一些项(靠分别把它们放进去来处理),而不是总是一对一。从这个意义上讲,它的作用类似于
filter的对立面。只需返回一个1项元素数组以保留该项,返回一个多元素数组以添加项,或返回一个0项元素数组以删除该项。