JavaScript 数组(Array) 方法

JavaScript array.flat() 方法是数组的内置方法,它可以将给定多维数组转为新创建的一维数组。

语法

var newArr=arr.flat(<depth>);

参数

depth:这是一个可选参数,用于指定转换数组的深度。默认情况下,它的值为 1。

返回值

它返回一个新创建的数组,其中包含连接到其中的所有子数组元素。

方法示例

让我们看下面的例子来更好地理解 array.flat() 方法的使用方法

示例1

二维数组上 flat() 方法的简单工作。

<html>
<head> <h5> Array 方法</h5> </head>
<body>
<script>
var arr=['a','b',['c','d']]; //2维数组
var newArr=arr.flat(); //使用flat()方法
document.write("调用flat函数后为:  "+newArr);
</script>
</body>
</html>

输出:

调用flat函数后为: a,b,c,d

示例2

使用 flat() 方法测试多维数组。

<html>
<head> <h5> Array 方法</h5> </head>
<body>
<script>
var arr=[90,18,[89,56],[13,20,[67,17]]]; //多维数组
var newArr=arr.flat(); //使用 flat() 方法
document.write("调用flat函数后为:  "+newArr);
</script>
</body>
</html>

输出:

很明显,数组中的每个元素都连接到新创建的一维数组。

调用flat函数后为: 90,18,89,56,13,20,67,17

示例3

让我们将数组展平到指定的深度。

<html>
<head> <h5> Array Methods </h5> </head>
<body>
<script>
var arr=[90,18,[13,20,[67,17,[56,45]]]]; //given multidimensional array
var newArr=arr.flat(3); //using flat() method with a specified depth value.
document.write("After flattening the array:  "+newArr);
</script>
</body>
</html>

输出:

After flattening the array: 90,18,13,20,67,17,56,45

示例4

使用 flat() 方法,深度值为无穷大。

<html>
<head> <h5> Array 方法</h5> </head>
<body>
<script>
var arr=['Orange','Pineapple','Grapes',['Potato','Tomato','Carrot',['Guava','Litchi']]]; //给定一个多维数组
var newArr=arr.flat(Infinity); //设置深度
document.write("After flattening the array,the new array comes out: <br> "+newArr);
</script>
</body>
</html>

输出:

After flattening the array,the new array comes out:
Orange,Pineapple,Grapes,Potato,Tomato,Carrot,Guava,Litchi

示例5

<html>
<head> <h5> Array 方法</h5> </head>
<body>
<script>
var arr=['John','Peter',,'Tomy',['Eni',,'Kerry']]; //给定一个中间有空隙的2维数组
var newArr=arr.flat(); //使用flat() 方法.
document.write("After flattening the array, the holes vanishes. The new array comes out: <br> "+newArr);
</script>
</body>
</html>

输出:

After flattening the array, the holes vanishes. The new array comes out:
John,Peter,Tomy,Eni,Kerry