JavaScript Array flat()

flat() 方法通过将嵌套数组展平到指定深度来创建一个新的数组

示例

// 3 nested arrays 
let numbers = [1, 2, [3, 4, [5, 6, [7, 8]]]];

// reducing nesting by flattening the array to depth 2 let flattenArray = numbers.flat(2);
// new flatten array console.log(flattenArray); // Output: // [ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]

flat() 语法

flat() 方法的语法是:

arr.flat(depth)

这里,arr 是一个数组。


flat() 参数

flat() 方法接受一个**单个**参数:

  • depth - 一个整数,指定嵌套数组应展平的深度。默认值为 **1**。

flat()返回值

  • 返回一个展平后的数组,并将子数组元素连接到其中。

注意flat() 方法

  • 不会改变原始数组。
  • 会删除数组中的空位。

示例 1:使用 flat() 方法

// 3 nested array 
let numbers = [1, 2, [3, 4, [5, 6, [7, 8]]]];

// reducing nesting by flattening the array to depth 2 let flattenArray = numbers.flat(2);
// new flatten array console.log(flattenArray);

输出

[ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]

在上面的示例中,我们使用 flat() 方法将嵌套数组 numbers 展平到深度 **2**。

numbers.flat(2) 减少了 numbers 数组的嵌套,并返回一个只有一个嵌套层级的展平数组,即 [ 1, 2, 3, 4, 5, 6, [ 7, 8 ] ]


示例 2:flat() 不带默认深度参数

// nested array
let array1 = [1, [2, 3, 4], 5];

// without passing any depth argument in flat() let flattenArray = array1.flat();
console.log(flattenArray);

输出

[ 1, 2, 3, 4, 5 ]

在此示例中,我们没有在 flat() 方法中传递任何深度参数。

默认深度参数为 **1**,因此 array1.flat()array1 展平到深度 **1**。


示例 3:flat() 用于移除数组中的空位

我们可以使用 flat() 方法移除包含空位的数组中的空位。例如:

// array with empty slots
let array_with_holes = [1, , 3];

// removes holes in the array let flattedArray = array_with_holes.flat();
console.log(flattedArray); // [ 1, 3 ]

输出

[ 1, 3 ]

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战