为什么这些Eloquent Javascript Chessboard解决方案中的一个比另一个好

时间:2015-03-19 00:05:52

标签: javascript

我从Eloquent Javascript这本书中获取了Chessboard拼图,并设计了以下解决方案,而没有看到提示

var newline = "\n";
var counter = .5;
var string1 = " # # # #";
var string2 = "# # # # ";
while (counter <= 3.5){
  console.log(string1 + newline);
  console.log(string2 + newline);
  counter++
}

我原本写了太多的线条,所以简单地将我的计数器改为“半步”。 通过查看其他人如何实现这一目标,我找到了解决方案。

    var size = 8;
for (var i = 0; i < size; i++) {
  var line = "";
  for (var j = 0; j < size; j++) {
    var total = i + j;
    if (total % 2 == 0) { 
      line += '#';
    } else {
      line += ' ';
    }
  }
  console.log(line);
}

你能解释为什么一个版本可能比另一个版本更好吗?此外,对第二个的简明英语解释会有所帮助。我试着用一种简单的评论来谈论自己很头疼。

1 个答案:

答案 0 :(得分:1)

第二个简单的英语解释 - var size = 8将是董事会的规模。第一个for循环声明var line并最终将其记录到控制台。如果您愿意,它将记录每个行或行的控制台。

第二个for循环实际上会构建行或行,为行中的每一列添加var line。它不必像在第一个版本中那样声明两个字符串,而是根据一些变量和规则知道每一行应该如何结束。规则是如果total可被2整除,则添加“#”,如果没有,则添加“”。 total的计算方法是添加ij

因此,在第一行i始终为0,j将为0,然后是1,然后是2,等等......所以total可以被2整除,然后不是可以被2整除,然后可以被2整除......然后在第二行i将等于1,j再次为0,然后是1,然后是2,等等。现在total首先不会被2整除,然后可以被2整除,然后不会被等等......对于第三行,i将为2,这基本上将作为i为0,因为0和2都除以2时没有余数。这就是第二个for循环与string1string2完成相同的操作。对不起,这有点罗嗦,希望有道理......我会在下面的实际代码中加入一些评论。

// sets size of board, since the first loop will run for this amount of
// times, and log a row to console each time, and the second loop will add   
// this many characters to the string to be logged.
var size = 8;

// first loop, which will run a number of times equal to the size
// variable, and log a row to console each time
for (var i = 0; i < size; i++) {

  // declares the string to be logged as the row
  var line = "";

  // this loop will run a number of times equal to the size
  // variable, and add a character to the line variable each time,
  // either a "#" or a " "
  for (var j = 0; j < size; j++) {

    // the total variable will be used to determine if the character added
    // to the line is a "#" or a " "
    // basically, any time i is 0 or divisible by 2, the row will
    // begin with a "#" and alternate from there as j changes, 
    // if i is not divisible by 2, the row will begin with a " " 
    // and alternate from there
    var total = i + j;

    // this if else statement actually uses total to added either "#" or " "
    if (total % 2 == 0) { 
      line += '#';
    } else {
      line += ' ';
    }
  }

  // this is outside of the second loop, and now the line variable is done
  // being added to, and the line is logged
  console.log(line);
}