繁体   English   中英

使用 JavaScript 中的 fill() 方法简化二维数组的创建

[英]Simplifying a two-dimensional array creation with the fill() method in JavaScript

 const hole = 'O'; // Declare constant for the hole character const fieldCharacter = '░'; // Declare constant for the field character // Initialize a field with a given height, width, and percentage of holes function initiliazeField(height, width, percentage) { // Return either the hole or field character based on the percentage // If the percentage is not between 0 and 35, log an error message const fieldOrHole = (percentage) => { return percentage >= 0 && percentage <= 35? Math.floor(Math.random() * 35) < percentage? hole: fieldCharacter: console.log('Please enter a number between 0 - 35'); } // Initialize an empty array to hold the rows of the field const rows = []; // Create rows for the field for (let i = 0; i < height; i++) { // Initialize an empty array to hold the characters in the row const row = []; // Populate the row with the appropriate character based on the percentage for (let j = 0; j < width; j++) { row.push(fieldOrHole(percentage)); } // Add the row to the field rows.push(row); } // Map each element in the rows array to a new array, and log each row to the console return rows.map(subArray => subArray.map(element => element)).forEach(row => console.log(row.join(' '))); }; // Print the initialized field to the console console.log(initiliazeField(20, 20, 20)); Output: // Expected a randomly generated two-dimensional array ░ ░ ░ OO ░ O ░ OOOOO ░ ░ OO ░ ░ O ░ O ░ ░ O ░ OOOOOOO ░ O ░ ░ O ░ O ░ OO ░ O ░ O ░ ░ O ░ ░ ░ OO ░ OOO ░ O ░ ░ ░ O ░ O ░ ░ ░ OOO ░ ░ ░ OO ░ OO ░ ░ O ░ ░ ░ ░ O ░ OO ░ ░ ░ ░ OO ░ O

此代码定义了一个函数initiliazeField() ,它生成一个二维数组,表示具有给定高度、宽度和孔洞百分比的字段。 该字段表示为一个行数组,每一行都是一个字符数组。 这些字符是空洞 ('O') 或字段字符 ('░')。

该函数采用三个参数:

  • height :字段的高度,表示为字段中的行数。

  • width :字段的宽度,表示为字段中的列数。

  • percentage :字段中孔的百分比(必须是 0 到 35 之间的数字) 该函数首先定义一个嵌套函数 fieldOrHole(),它根据给定的百分比返回孔或字段字符。 如果百分比不在 0 到 35 之间,则会将错误消息记录到控制台。

然后该函数初始化一个空的行数组来保存字段的行。 它通过遍历循环并使用高度参数来确定行数来为字段创建行。 在循环中,它初始化一个空数组行来保存行中的字符,并使用嵌套循环用字符填充行。 宽度参数用于确定行中的列数。 每个位置的字符通过调用fieldOrHole()函数来确定。

最后,该函数将行数组中的每个元素映射到一个新数组,并使用forEach()方法将每一行记录到控制台。 map()forEach()方法用于遍历行数组并将每一行记录到控制台。 join(' ')方法用于将行中的元素与空格字符连接起来,因此输出格式正确。

如何使用 fill() 方法简化initiliazeField()函数?

你可能想使用Array.from

 const gen = (height, width, percentage) => Array.from( {length: height}, ()=>Array.from( {length: width}, ()=>Math.random()*100 < percentage? '0': '░' ) ); const A = gen(7, 10, 20); console.log(A.map(a => a.join('')).join("\n"));

我排除了 I/O 部分,因为将它与生成矩阵的代码分开是有意义的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM