2011-12-02 103 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