推荐答案
Array.prototype.flat() 和 Array.prototype.flatMap() 是 JavaScript 中用于处理嵌套数组的两个重要方法。
flat() 方法会创建一个新数组,将原数组中所有子数组拼接起来,并根据指定的深度进行扁平化处理。其基本语法为 arr.flat([depth]),其中 depth 是一个可选参数,用于指定扁平化的深度,默认为 1。如果 depth 为 Infinity,则会完全扁平化数组。
flatMap() 方法首先使用映射函数处理原数组的每个元素,然后将结果扁平化为新数组,其行为类似于 arr.map(...).flat(1)。其基本语法为 arr.flatMap(callback(currentValue[, index[, array]])[, thisArg]),它接受一个回调函数,该回调函数类似于 map 方法中的回调函数,返回一个数组,flatMap() 将会把这些数组展开并连接成一个新数组。
简而言之,flat() 用于扁平化数组,而 flatMap() 用于映射并扁平化数组。
本题详细解读
Array.prototype.flat() 的详细解释
作用
flat() 方法用于将嵌套的多维数组扁平化为一个一维数组。它可以接收一个可选的深度参数 depth,用于指定扁平化的层数。
语法
arr.flat([depth])
depth(可选):一个指定扁平化层数的数字。默认值为 1。可以使用Infinity作为depth,表示完全扁平化数组。- 返回值:一个新的扁平化后的数组。
用法示例
// www.javascriptcn.com code example // 默认扁平化一层 const arr1 = [1, 2, [3, 4]]; console.log(arr1.flat()); // 输出: [1, 2, 3, 4] // 指定扁平化深度 const arr2 = [1, 2, [3, 4, [5, 6]]]; console.log(arr2.flat(1)); // 输出: [1, 2, 3, 4, [5, 6]] console.log(arr2.flat(2)); // 输出: [1, 2, 3, 4, 5, 6] // 使用 Infinity 完全扁平化 const arr3 = [1, 2, [3, 4, [5, 6, [7, 8]]]]; console.log(arr3.flat(Infinity)); // 输出: [1, 2, 3, 4, 5, 6, 7, 8] // 数组中存在空槽的情况, flat会移除空槽 const arr4 = [1, 2, ,4, ,5]; console.log(arr4.flat()) // [ 1, 2, 4, 5 ]
Array.prototype.flatMap() 的详细解释
作用
flatMap() 方法首先使用给定的回调函数映射数组的每个元素,然后将映射产生的新数组扁平化为一个新数组。它等效于 arr.map(callback).flat(1),但效率更高。
语法
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
callback:一个用于产生新数组的函数,接受三个参数:currentValue:当前正在处理的元素。index(可选):当前元素的索引。array(可选):调用flatMap()的数组本身。
thisArg(可选):执行callback时使用的this值。- 返回值:一个新的扁平化后的数组。
用法示例
// www.javascriptcn.com code example
const arr5 = ["it's sunny day", "today is a new day"];
const result = arr5.flatMap(str => str.split(' '));
console.log(result); // 输出: ["it's", "sunny", "day", "today", "is", "a", "new", "day"]
// 使用 map + flat 达到相同的效果 (相当于 flatMap(callback))
const result2 = arr5.map(str => str.split(' ')).flat();
console.log(result2); // 输出: ["it's", "sunny", "day", "today", "is", "a", "new", "day"]
// 使用索引
const arr6 = [1, 2, 3];
const result3 = arr6.flatMap((value,index) => {
if (index % 2 === 0){
return [value , value * 2]
}else {
return value
}
})
console.log(result3) // [ 1, 2, 2, 3, 6 ]关键区别
flat()主要用于扁平化数组,它不改变数组元素的值。flatMap()主要用于映射和扁平化数组,它会先通过一个回调函数处理原数组元素,然后再扁平化结果。flatMap()的扁平化深度始终为 1,而flat()可以指定不同的扁平化深度。- 从效率上来说,
flatMap比arr.map(...).flat(1)效率更高。