JavaScript 如何将给定的数组按指定的深度展开

JavaScript 如何将给定的数组按指定的深度展开

本文中,我们将学习如何在JavaScript中将给定的数组按指定的深度展开。

JavaScript中的 flat()方法 用于按需展开数组。它创建一个新的数组,并递归地连接原始数组的子数组,直到达到给定的深度。该方法只接受一个可选的深度参数(默认为1)。该方法也可以用于删除数组中的空元素。

语法:

array.flat(depth);

示例:

// Define the array
let arr = [1, [2, [3, [4, 5], 6], 7, 8], 9, 10];
 
console.log("Original Array:", arr);
 
let flatArrOne = arr.flat();
 
console.log("Array flattened to depth of 1:"
            + flatArrOne);
 
let flatArrTwo = arr.flat(2);
 
console.log("Array flattened to depth of 2:"
            + flatArrTwo);
 
let flatArrThree = arr.flat(Infinity);
 
console.log("Array flattened completely:"
            + flatArrThree);

输出

Original Array: [ 1, [ 2, [ 3, [Array], 6 ], 7, 8 ], 9, 10 ]
Array flattened to depth of 1:1,2,3,4,5,6,7,8,9,10
Array flattened to depth of 2:1,2,3,4,5,6,7,8,9,10
Array flattened completely:1,2,3,4,5,...

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程