理解Eloquent JS(练习2.3)

时间:2015-07-21 16:44:55

标签: javascript if-statement

我正在使用Eloquent Javascript,Chess Board进行第2章练习3。我有一个问题理解一个部分,并希望有人能够提供一点启示。

我的代码:

var size = 7;
var board = "";
for(var i = 0; i <= size; i++){
    for(var j = 0; j <= size; j++){
        if((i + j) % 2 === 0){
            board += " ";
        } else {
            board += "#";
        }
    }
    board += "\n";
}
console.log(board);

我遇到的问题是“if”声明的条件。

if((i + j) % 2 === 0)

我不明白为什么我需要将i和j加在一起。是不是第一个“for”循环包含构造行的i变量和多少行?其中,包含j变量的第二个“for”循环是在每行中创建内容吗?

3 个答案:

答案 0 :(得分:1)

它正在创建一个棋盘格模式,因此每次迭代时各行都会关闭一行。如果没有使用该行,则会产生条纹。

目前有i + j % 2

  # # # #
 # # # # #
  # # # #
 # # # # #

如果只是j % 2

  # # # #
  # # # #
  # # # #
  # # # #

如果只是i % 2

.
 ########

 ########

 ########

答案 1 :(得分:1)

添加i和j是创建棋盘图案。如果总和是偶数,则打印白色方块(&#34;&#34;);否则它是黑色的(&#34;#&#34;)。

此外,您的条件语句包含三等号而不是所需的==。

答案 2 :(得分:1)

我觉得我回答有点迟,但无论如何都会这么做。

因为你想创建一个看起来像这样的模式。

"# # # #"
" # # # "

因此你要添加变量&#34; i&#34;用来计算你的外循环和变量&#34; j&#34;来自用于计数的内循环,在if / else语句的帮助下输出&#34;#&#34;或&#34; &#34;(空间)。也不是说你的第一个外环将保持在0直到可修复的&#34; j&#34;在你的内循环中等于&#34;大小&#34;。意味着第一次运行(i + j)= = 0 + 1,0 + 2,0 + 3,0 + 4,0 + 5,0 + 6,0 + 7。一旦内循环完成,外循环就会添加一个&#34; \ n&#34;并且procces重复,但这次你的外环可变,用于计数从0到1的变化,你的内部循环变量用于计数重置为0,你的表达式(i + j)现在等于1 + 0 ,1 + 2,1 + 3等

var size = 7;
var board = "";
for(var i = 0; i <= size; i++){ /*This will remain 0 the first run until the inner loop is completed then it will add the "\n" at the end*/
for(var j = 0; j <= size; j++){/* the variable j here will keep adding 1 to itslef until it j is equal to size*/
    if((i + j) % 2 === 0){/* here it will add both i+j then divide it by 2 in order to see if is an even number or not. 
                            remember it will look something like the this first run 0+1, 0+2, 0+3 ect.*/
        board += " ";// here if the number is even it will output a (space) 
    } else {
        board += "#";// here if the number is not even it adds "#"
    } // finally this inner loop gets repeated until your vairable "j" is equal to "size" 
}
board += "\n";/* then the outer loop adds a new line and your vairable "i" 
              becomes 1 and this whole loop gets reapeated until "i" is equal to "size"*/
}
console.log(board);    

希望这有助于解释我的语法,我的英语不是墨西哥城那么好的问候