我的代码正在尝试组装一个给定大小的可视棋盘,然后将其输出到 console.log
。基本上,它:
- 循环面板中的所有行
- 循环遍历该行中的所有列
- 如果列位于偶数行中,则会放置一个空格
- 如果列位置在奇数行中为偶数,则会放置一个黑色空格。
我的代码:
var sz = Number(prompt("What size chessboard?"))
console.log("Board of size " + sz + " selected.")
var row = 0
var rowType = "even"
var col = 0
var bd = ""
var whiteSpace = "[]"
var blackSpace = "()"
for (row; row <= sz; row++) {
if (row % 2 == 0) {rowType = "even";} // For even rows, all even column places are white
else {rowType = "odd";} // and for odd rows, all even column places are black
for (col = 0; col <= sz; col++) {
if (col % 2 == 0) {
if (rowType == "even") {bd += whiteSpace;}
if (rowType == "odd") {bd += blackSpace;}
else {console.log("Something went terribly wrong.")} // This should never happen... right?
}
else {
if (rowType == "even") {bd += blackSpace;}
if (rowType == "odd") {bd += whiteSpace;}
else {console.log("Something went horribly wrong.")} // Not this one either?
}
}
bd += "\n"
}
console.log(bd)
出于某种原因,我输入的额外代码只是为了捕获 if 的情况,不知何故,rowType
似乎总是不执行“偶数”或“奇数”,将“发生了可怕/可怕的错误”放在 console.log
中即使代码运行良好并且电路板实际上已正确生成。
我的问题不在于如何删除这些行,显然我可以删除 else
block ,但我很好奇我的错误在哪里,导致它首先运行。
有什么想法吗?
最佳答案
当你拥有它时,你正在做:
if (rowType == "even") {bd += whiteSpace;}
if (rowType == "odd") {bd += blackSpace;}
else {console.log("Something went terribly wrong.")} // <- will execute if
// not 'odd'
应该是:
if (rowType == "even") {bd += whiteSpace;}
else if (rowType == "odd") {bd += blackSpace;}
else {console.log("Something went terribly wrong.")} // <- will execute if
// not 'even' or 'odd'
关于Javascript - if 和 else 语句都执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498539/