2012-01-31 174 views
0

我已經得到了以下代碼IF條件代碼:IF-ELSE條件 - 運行在ELSE部分

if ((depth <= min_depth) && (leaf_colour == "red")){ 

    for (i = 0; i < array_2D.length; i++) { 
     var leaf_size = array_2D[i][1]; 

     if (leaf_size == 10 || leaf_size == 11){ 
      alert("Error message."); 
      break; // we found an error, displayed error message and now leave the loop 
     } 
      else{ go to the next else section } 
    } 
}//end of if condition 

else{ 

    ... 
    ... 
    ... 
    ... 
    ... 

} 

裏面的 'for' 循環,如果(leaf_size == || 10 == leaf_size 11 ),我們打破循環,什麼都不做,但如果不是這樣,我想在下一個ELSE部分運行代碼。

我不想複製整個代碼塊並將其粘貼到for循環的'else'部分,因爲它很長。

有沒有辦法在第二個其他部分運行代碼?

+1

移動從第二個'else'塊中的代碼到一個單獨的功能及調用該函數在這兩種情況下? – 2012-01-31 11:41:51

+0

也許將ELSE部分中的代碼移到一個函數並調用它兩次 – Insidi0us 2012-01-31 11:42:42

+0

謝謝,我會嘗試 – Kim 2012-01-31 11:44:52

回答

1
var ok = (depth <= min_depth) && (leaf_colour == "red"); 
if (ok){ 

    for (i = 0; i < array_2D.length; i++) { 
     var leaf_size = array_2D[i][1]; 

     if (leaf_size == 10 || leaf_size == 11){ 
      alert("Error message."); 
      ok = false; 
      break; 
     } 
     else{ 
       ok = true; 
       break; 
      } 
    } 
}//end of if condition 

if(!ok) { 

    ... 
    ... 
    ... 
    ... 
    ... 

} 
+0

謝謝你的解決方案..它的工作很棒 – Kim 2012-01-31 11:53:07

2

您需要將代碼從第二個else塊移入單獨的函數。然後,您可以調用該函數,無論你需要運行該代碼:

function newFunction() { 
    //Shared code. This is executed whenever newFunction is called 
} 

if(someCondition) { 
    if(someOtherCondition) { 
     //Do stuff 
    } 
    else { 
     newFunction(); 
    } 
} 
else { 
    newFunction(); 
}