2012-10-14 177 views
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; 
     } 
     }  
    } 
+0

@Blender,你可以給任何幫助將不勝感激。 – KMcA

+0

看到我的答案。它應該讓事情更清楚一些。另外,如果您發現答案可以回答您的問題,請檢查綠色選中標記(您似乎忘記爲以前的問題執行此操作)。 – Blender

回答

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; 
}​ 

從我所知道的情況來看,這段代碼計算連續井號的數量,並將這段文字追加到每一行。

+0

對不起,如果這是一個愚蠢的問題,但我對行rowCount [i] + = spaceCount +「0123C 」之後rowCount [i]的值感到困惑。「spaceCount的值如何1),被添加到rowCount [i]? – KMcA

+0

您正在使用'+ ='運算符。 'a + = 1'相當於'a = a + 1'。 – Blender

+0

我也看不到else if語句(spaceCount> 0)是否會成爲真,因爲我們將spaceCounter的值設置爲0,並且只將它作爲if語句的一部分增加? – KMcA