我对javascript很陌生,我试图打印出一个带有"#"符号的棋盘。我想问用户:"你希望你的棋盘有多宽?"当用户输入他们想要的数字时,我想把这个字符串转换成一个数字,这样我就可以用它来创建电路板。例如,如果用户输入= 8,控制台将打印如下模式(8x8):
# # # # # # # #
# # # # # # #
# # # # # # # #
# # # # # # #
# # # # # # # #
# # # # # # #
# # # # # # # #
# # # # # # #
这是我目前为止写的:
var userInput = prompt("How wide do you want your chessboard to be?")
var userInput = Number(userInput)
var string1 = Array(userInput).join(" #")
var string2 = Array(userInput).join("# ")
var newline = "n"
var counter = 0.5
var chessboard = function () {
console.log(string1 + newline + string2);
};
while (counter <= userInput/2) {
console.log(chessboard);
counter++
};
问题是你如何调用chessboard
,你正在传递一个函数引用到console.log()
,所以它将记录函数。
由于您的chessboard
方法打印字符串,只需调用chessboard
方法,如
while (counter <= userInput/2) {
chessboard();
counter++
};
但是这里有一个逻辑问题,如果用户输入7
会发生什么,所以
var elboard = document.getElementById('board');
var userInput = prompt("How wide do you want your chessboard to be?");
var userInput = Number(userInput);
var string1 = Array(userInput + 1).join(" #")
var string2 = Array(userInput + 1).join("# ")
var newline = "n"
var chessboard = function(i) {
var string = i % 2 == 0 ? string1 : string2;
console.log(string)
elboard.appendChild(document.createTextNode(string + 'n'));
};
for (var i = 0; i < userInput; i++) {
chessboard(i);
};
#board {
white-space: pre;
}
<div id="board"></div>