[笔记]JS flat and flatMap

原文
flat()接收一个数组(这个数组中的某些item本身也是一个数组),返回一个新的一维数组(如果没有特别指定depth参数的话返回一维数组)。

const nestedArraysOhMy = [ "a", ["b", "c"], ["d", ["e", "f"]]];
// .flat() 接收一个可选的深度参数
const ahhThatsBetter = nestedArraysOhMy.flat( 2 );
console.log( ahhThatsBetter ); // [ "a", "b", "c", "d", "e", "f" ]

flatMap()类似于map(),但是它的callback返回的是扁平的一维数组(如果没有特别指定depth参数的话)。

const scattered = [ "my favorite", "hamburger", "is a", "chicken sandwich" ];

// map() 返回的是嵌套的数组results in nested arrays
const huh = scattered.map( chunk => chunk.split( " " ) );
console.log( huh ); // [ [ "my", "favorite" ], [ "hamburger" ], [ "is", "a" ], [ "chicken", "sandwich" ] ]

const better = scattered.flatMap( chunk => chunk.split( " " ) );
console.log( better ); // [ "my", "favorite", "hamburger", "is", "a", "chicken", "sandwich" ]
posted @ 2019-02-22 08:33  irocker  阅读(2279)  评论(0编辑  收藏  举报