JavaScript 中的 Array.flat()
你好,开发者们,
在本文中,我将向您介绍 JavaScript 中数组的重要方法之一,即 Array.flat 方法。
目录
所以,不要浪费时间,让我们进入正文
理论
flat() 方法用于展平数组。展平的过程取决于我们想要展平数组的深度。
此方法的作用是,从数组的数组中取出数组元素并将它们连接到主数组中。
它将重复此过程直到达到深度值。
句法
Syntax:
flat(depth)
// The depth level specifying how deep a nested array structure should be flattened.
// Defaults to 1.
返回值
return value:
A new array with the sub-array elements concatenated into it.
示例
注意:如果你想将数组展平到最后的深度,那么depth
就把Infinity
example:
let arr = [1, 2, [3, 4, [5, 6]]];
arr.flat(0) // [1, 2, [3, 4, [5, 6]]];
arr.flat(1) // [1, 2, 3, 4, [5, 6]]
arr.flat(2) // [1, 2, 3, 4, 5, 6]
arr.flat(3) // [1, 2, 3, 4, 5, 6]
arr.flat( ) // [1, 2, 3, 4, [5, 6]]
// if no depth is provided then it will take the default value i.e 1.
arr.flat(Infinity) //[1, 2, 3, 4, 5, 6]
arr.flat(0).length //3
arr.flat(1).length //5
arr.flat(2).length //6
感谢您阅读到这里。本文是对 JavaScript 中 Array.flat() 方法的简要介绍。
如果您觉得本文有用,请点赞并分享。或许有人也会觉得它有用。如果您发现任何技术上不准确的地方,请随时在下方评论。
希望这篇文章对您来说有趣且内容丰富。
访问https://www.capscode.in/#/blog了解更多……
下篇博客文章再见,保重!!