我的代码正在尝试组装给定大小的可视棋盘,然后将其输出到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)
&#13;
出于某种原因,我提出的额外代码只是为了捕捉if {02}}的情况,而不是&#34;甚至&#34;或&#34;奇数&#34;似乎总是执行,把...&34;某些事情变得非常/非常错误&#34;在rowType
,即使代码工作正常,董事会实际上是正确生产的。
我的问题不是如何摆脱这些界限,显然我可以删除console.log
块,但我很好奇我的错误在哪里使它成为现实跑在第一位。
有什么想法吗?
答案 0 :(得分:3)
如你所愿,你正在做:
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'