0

下面的代码是我正在学习的初学者拼图应用教程的包含文件。该代码有效,但是现在我已经完成了教程,我正在尝试阅读预加载的未解释的文件。

我真的被“spacecount”变量绊倒了,它到底在做什么。任何人都可以用简单的英语评论每一行,这样我就可以更好地理解下面的代码是如何填充 rowCount 数组的。太感谢了。

var totalRows = puzzle.length;
var totalCols = puzzle[0].length;

/* Loop through the rows to create the rowCount array 
containing the totals for each row in the puzzle */

var rowCount = [];
for (var i = 0; i < totalRows; i++) {
  rowCount[i]="";
  spaceCount = 0;

  for (var j = 0; j < totalCols; j++) {
     if (puzzle[i][j] == "#") {
        spaceCount++; 

       if (j == totalCols-1) rowCount[i] += spaceCount + "&nbsp;&nbsp;";
       } else {
          if (spaceCount > 0) {
           rowCount[i] += spaceCount + "&nbsp;&nbsp;";
           spaceCount = 0;
        } 
      }    
    }
4

1 回答 1

0

这是一个更清晰的版本:

var totalRows = puzzle.length;
var totalCols = puzzle[0].length;

/* Loop through the rows to create the rowCount array 
containing the totals for each row in the puzzle */

var rowCount = [];

for (var i = 0; i < totalRows; i++) {
    rowCount[i] = "";
    spaceCount = 0;

    for (var j = 0; j < totalCols; j++) {
        if (puzzle[i][j] == "#") {
            spaceCount++;

            if (j == totalCols - 1) {
                rowCount[i] += spaceCount + "&nbsp;&nbsp;";
            }
        } else if (spaceCount > 0) {
            rowCount[i] += spaceCount + "&nbsp;&nbsp;";
            spaceCount = 0;
        }
    }
}​

令人困惑的部分可能是if中间的块。

if (puzzle[i][j] == "#") {     // If a puzzle piece is `#` (a space?)
    spaceCount++;              // Increment the spaceCount by 1.

    if (j == totalCols - 1) {  // Only if we are on the last column, add the text
                               // to the row.
        rowCount[i] += spaceCount + "&nbsp;&nbsp;";
    }
} else if (spaceCount > 0) {   // If the current piece isn't a `#` but 
                               // spaces have already been counted,
                               // add them to the row's text and reset `spaceCount`
    rowCount[i] += spaceCount + "&nbsp;&nbsp;";
    spaceCount = 0;
}​

据我所知,此代码计算连续磅符号的数量并将此文本附加到每一行。

于 2012-10-14T20:13:42.240 回答