2012-01-31 176 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(); 
}