我想使用2 for循环将类似(你可以在下面找到)这样的东西绘制成一个字符串数组。
let matrix = [
"....................",
".000000000000000000.",
".0................0.",
".0.00000000000000.0.",
".0.0............0.0.",
".0.0.0000000000.0.0.",
".0.0.0........0.0.0.",
".0.0.0.000000.0.0.0.",
".0.0.0.0....0.0.0.0.",
".0.0.0.0.00.0.0.0.0.",
".0.0.0.0.00.0.0.0.0.",
".0.0.0.0....0.0.0.0.",
".0.0.0.000000.0.0.0.",
".0.0.0........0.0.0.",
".0.0.0000000000.0.0.",
".0.0............0.0.",
".0.00000000000000.0.",
".0................0.",
".000000000000000000.",
"....................",
]
console.log(matrix)
注意:我希望能够指定模%
(相同字符的行和列的宽度,在一种情况下,在另一种情况下更大)一个更小的模式。
这是我到目前为止的代码。目前它只能从topLeft到bottomRight绘制一个“对角线”。
let matrix = [
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
"00000000000000000000",
]
for (let y=0; y<matrix.length; y++) {
for (let x=0; x<matrix[y].length; x++) {
if (x==y) {
let row = matrix[y].split("")
row[x] = ".";
matrix[y] = row.join("")
}
}
}
console.log(matrix)
任何帮助都会非常感激。
答案 0 :(得分:0)
您可以使用迭代方法检查外框并转到内部较小的框架,通过使用数组作为角点的起点进行检查。
var length = 20,
even = Array.from({ length: length >> 2 }, (_, i) => i << 1),
result = Array.from({ length }, (_, i) => Array.from({ length }, (_, j) =>
even.some(v =>
i >= v && i <= length - 1 - v && (j === v || j === length - 1 - v) ||
(i === v || i === length - 1 - v) && j >= v && j <= length - 1 - v)
? '.'
: 'x'
).join(' '));
document.getElementById('out').innerHTML = result.join('\n');
<pre id="out"></pre>