The aim is to write function drawACross
which returns a cross shape with 'x'
characters on a square grid of size and height of our sole input n
. All non-'x'
characters in the grid should be filled with a space character (" "
).
The arms of the cross must only intersect through one central 'x'
character, and start in the corner of the grid, so for even values of n
, return "Centered cross not possible!"
If n < 3
, function should return "Not possible to draw cross for grids less than 3x3!"
This is my code, but in the result the cross is not centered:
function drawACross(n) {
if (n % 2 === 0) {
console.log("Centered cross not possible!")
} else if (n < 3) {
console.log("Not possible to draw cross for grids less than 3x3!")
} else {
for (let i = 0; i < n; i++) {
let arr = new Array(n)
let y = arr.fill("", 0, arr.length)
y.splice(arr.length - (i + 1), 1, "x")
y.splice(i, 1, "x")
console.log(y.join(" "))
}
}
}
drawACross(5);
question from:
https://stackoverflow.com/questions/65951294/how-can-i-draw-a-cross-in-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…