2011-12-02 112 views
0

夥計們,我正在稍微修改一個當前函數以利用兩個 變量。我已經在代碼片段中展示了過去和現在的版本。
基本上我想要的是如果兩個if conditions的首要條件第二個條件的任何一個都 是真實的,不執行該功能的其餘邏輯。如果兩者均爲false,則繼續使用該函數的其餘代碼。
我想我在某個地方犯了一個愚蠢的錯誤,如果第一個條件成立,那麼執行就停在那裏。 (我知道這是因爲在最後的return語句。) 如何確保第二,如果還有,即使第一個是真,返回returnJavascript如果返回條件

function myAlgorithm(code1, code2) { 

    if(eval(code1)) { 

     if(First condition) { 
     alert("You cant continue"); 

     return; 
     } 
    } 

    if(eval(code2)) { 
     if(Second condition){ 
     alert("You cant continue"); 
     return; 
     } 

    } 

    //If both of the above if conditions say "You cant continue", then only 
    //disrupt the function execution, other wise continue with the left 
    //logic 

    //Rest of the function logic goes here 

} 

Ealier使用該代碼的條件成爲:

function myAlgorithm() { 

    if((First Condition) && (Second Condition)){ 
    alert("You cant continue"); 

    return; 
    } 

    //Rest of the function logic goes here 
} 
+2

什麼樣的? – SLaks

+0

無論哪個條件都成立,你是否想要評估'code1'和'code2'?你有沒有注意到第二個'if'中的'return'放在了*括號之後? – Yogu

+0

你有沒有嘗試過返回True;或返回1;代替那些空的回報; –

回答

1

使用變量,並在條件滿足時增加它。然後檢查變量是否增加。

function myAlgorithm(code1, code2) { 
    var count = 0; 
    if (eval(code1)) { 

     if (First condition) { 
      alert("You cant continue"); 

      count++; 
     } 
    } 

    if (eval(code2)) { 
     if (Second condition) { 
      alert("You cant continue"); 
      count++; 
     } 
    } 
    if (count == 2) { 
     return "both conditions met"; 
    } 

    //If both of the above if conditions say "You cant continue", then only 
    //disrupt the function execution, other wise continue with the left 
    //logic 
    //Rest of the function logic goes here 
} 
+0

感謝真相。讓我試試這個真快。 – user1052591

0

能使用標誌變量來跟蹤你的條件,然後檢查他們兩個爲什麼你使用`eval`前

function myAlgorithm(code1, code2) { 
var flag1; 
var flag2 
if(eval(code1)) { 
    flag1 = First condition 
} 

if(eval(code2)) { 
    flag2 = second condition 
} 

if(flag1 && flag2){ 
    return; 
} 
//If both of the above if conditions say "You cant continue", then only 
//disrupt the function execution, other wise continue with the left 
//logic 

//Rest of the function logic goes here 

} 
+0

謝謝Decad ..我也會試試這個。 – user1052591

+0

哎呀有人降級你的解決方案......人們可以解釋爲什麼嗎? – user1052591