var board = ''
for (i=1;i<5;i ){
for (i=1;i<9;i ){
if (i%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
for (i=0;i<8;i ){
if (i%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
}
console.log(board);
當我嘗試運行此代碼時,輸??出是
O#O#O#O#
#O#O#O#O
預期的輸出是
O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O
O#O#O#O#
#O#O#O#O
我嘗試console.log(i)在第一個 for 陳述句之后添加一個right 并且它只回傳“1”,這意味著回圈只運行一次。為什么會這樣?
*編輯:當我將兩個內部 for 回圈包裝在一個函式中并呼叫它時,它按預期作業
uj5u.com熱心網友回復:
你是
- 為每個回圈使用相同的變數名:
i - 不為那些迭代變數使用塊作用域
let
因此i,您代碼中的所有參考都參考相同的系結。
在第二個內回圈結束時 - after for (i=0;i<8;i ){-i是 8。然后,外回圈:
for (i=1;i<5;i ){
看到i不小于5,所以它停止。
為每個回圈使用不同的變數名稱(例如i、j、 和k),并使用let. 兩者都可以解決它,但同時實施兩者是個好主意。
uj5u.com熱心網友回復:
我認為問題在于您在不同的回圈陳述句中重用了相同的變數i,因此內部回圈正在修改該變數的值。
例如。下面我使用不同的變數名。
var board = ''
// Main loop. This loop has two inner loops that writes a pair of lines in every iteration: the odd lines and pair lines.
// Note that the declared variable 'j' will be a available in the scope of this loop and any inner loop.
// Be aware that the variable 'j' will be used in this scope,
// but any modification (like reusing in another loop) will modify the variable value of 'j'.
// For this reason another variable are declared in the inner loops.
for (var j=1;j<5;j ){
// The first inner loop add the characters of the odd lines.
// To not modify the variable 'j' this loop declares another variable 'i'.
// This 'i' variable will be used for the columns of the odd lines.
for (var i=1;i<9;i ){
if (i%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
// The second inner loop add the characters of the pair lines.
// To not modify the variable 'j' this loop declares another variable 'k'.
// This 'k' variable will be used for the columns of the pair lines.
for (var k=0;k<8;k ){
if (k%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
}
console.log(board);
uj5u.com熱心網友回復:
var board = ''
for (j=1;i<5;i ){
for (i=1;i<9;i ){
if (i%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
for (i=0;i<8;i ){
if (i%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
}
console.log(board);
有兩個回圈,兩個都是索引的“i”。將一個改為'j'
uj5u.com熱心網友回復:
我嘗試過使用代碼進行試驗,這就是我得到的:
var board = ''
for (i1=0;i1<4;i1 ){
for (i2=0;i2<8;i2 ){
if (i2%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
for (i3=0;i3<8;i3 ){
if (i3%2 == 0){
board = "#";
}
else{
board = "O";
}
}
board = "\n"
}
console.log(board);
給我:
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
#O#O#O#O
問題是相同的變數 (i) 被重用,這意味著每個回圈都會重置變數。相反,我在初始 i 之后添加了數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364170.html
標籤:javascript 循环 for循环
