填充多维数组

时间:2012-10-14 20:02:04

标签: javascript multidimensional-array

下面的代码作为一个包含文件,带有我正在完成的初学者益智应用教程。代码工作,但是现在我已经完成了教程,我正在尝试阅读预装的文件,这些文件没有解释。

我真的绊倒了“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;
        } 
      }    
    }

1 个答案:

答案 0 :(得分: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;
}​

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