推荐答案
Array.prototype.flat 和 Array.prototype.flatMap 是 JavaScript 中用于处理嵌套数组的两个方法。
Array.prototype.flat: 该方法用于将嵌套的数组“拉平”,即将多维数组转换为一维数组。你可以通过传递一个可选的参数来指定拉平的深度,默认深度为 1。Array.prototype.flatMap: 该方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它相当于map和flat的组合,但flatMap的深度固定为 1。
本题详细解读
Array.prototype.flat
flat 方法用于将嵌套的数组“拉平”,即将多维数组转换为一维数组。你可以通过传递一个可选的参数来指定拉平的深度,默认深度为 1。
语法
arr.flat([depth])
depth(可选): 指定要拉平的深度,默认值为 1。
示例
const arr = [1, [2, [3, [4]]]]; console.log(arr.flat()); // [1, 2, [3, [4]]] console.log(arr.flat(2)); // [1, 2, 3, [4]] console.log(arr.flat(Infinity)); // [1, 2, 3, 4]
Array.prototype.flatMap
flatMap 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它相当于 map 和 flat 的组合,但 flatMap 的深度固定为 1。
语法
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
callback: 生成新数组元素的函数,接受三个参数:currentValue: 当前正在处理的元素。index(可选): 当前元素的索引。array(可选): 调用flatMap的数组。
thisArg(可选): 执行callback时使用的this值。
示例
const arr = [1, 2, 3]; console.log(arr.flatMap(x => [x * 2])); // [2, 4, 6] console.log(arr.flatMap(x => [[x * 2]])); // [[2], [4], [6]]
总结
flat用于将嵌套数组拉平为一维数组,可以指定拉平的深度。flatMap是map和flat的组合,先映射再拉平,但拉平深度固定为 1。