2011-11-08 83 views
2

以下是我的代碼: 此代碼用於查找與給定節點一起提供的周圍節點。OOP不產生預期的結果if語句和>符號

enter image description here

for(var i:uint = 0;i < nodes.length; i++){ 
      test_node = this.nodes[i]; 
      if (test_node.row < node.row - 1 || test_node.row > node.row + 1) continue; 
      if (test_node.column < node.column - 1 || test_node.column > node.column + 1) continue; 
      surrounding_nodes.push(test_node) 

     } 
/* 
nodes contains an array of objects. 
node is an object I want to use as my test variable. 
property row contains the row in which the object is located 
proerty column contains the cloumn in which the object is located 
*/ 

我得到正確的結果(因爲我下面的教程),雖然我不知道爲什麼?

這就是我在想什麼。

  1. 如果test_node行低於節點行位置,或者如果test_node 行是節點行的上方 - 繼續

  2. 如果test_node列是到節點列位置的左側繼續或如果test_node列位於 節點列的右側 - 繼續。

假設上面的圖像案例。
因此,不應該surround_nodes包含節點中的所有對象(bar是實際節點),因爲每個對象都將滿足上述語句,因爲和object將要在節點的上方或下方或左側或右側的。

這段代碼實際上做的只是找到節點周圍的節點(紅色方塊)。

有人真的可以幫助我理解這些if語句。

謝謝

回答

2

只是用數字替換條件,你看它是如何工作的。

在上述節點中的圖象是在4行和4列(從0開始),並讓我們test_node第2行 然後

if (test_node.row < node.row - 1 || test_node.row > node.row + 1) 

轉化爲

if (2 < 3 || 2 > 5) continue 

繼續裝置「跳過此迭代的其餘部分並開始下一個「

所以現在在第3行和第3列上取test_node

if (3 < 3 || 3 > 5) continue 
if (3 < 3 || 3 > 5) continue 

所有4個條件是假的,因此將其添加到surrounding_nodes

- 編輯 -

順便說一句,如果你標記你的循環是更加清晰易讀會發生什麼

iterateNodes : for(var i:uint = 0;i < nodes.length; i++){ 
    test_node = this.nodes[i]; 
    if (test_node.row < node.row - 1 || test_node.row > node.row + 1) continue iterateNodes; 
    if (test_node.column < node.column - 1 || test_node.column > node.column + 1) continue iterateNodes; 
    surrounding_nodes.push(test_node); 
} 
+0

owwwwwww,那是什麼'繼續'的意思。 現在非常有意義。 – dgamma3

+0

很高興現在很清楚,在我的答案中爲循環添加了一個標籤,使其更加清晰。 – Creynders