简体   繁体   English

如何在jQuery / Javascript中的三元运算符中返回(true / false)?

[英]How to return(true/false) in ternary operators in jQuery/Javascript?

How to use return in ternary operator in jQuery? 如何在jQuery中使用三元运算符返回?

myfunc: function() {
    for(i = 0; i < 10; i++) {
        (6 == i) ? Do_This_and_This : return true;
    }
    //Error: Expected an operand: but found return false or true.
}

As per understanding return false will return back to function and breaks the loop and return true will work as continue which moves to next iteration. 根据理解,返回false将返回功能并中断循环,返回true将作为继续到下一个迭代的继续工作。

Please validate understanding and provide solution for same. 请验证理解并提供解决方案。 If there is another way to do it please suggest 如果还有其他方法,请提出建议

UPDATE : My solution have big javascript and i have put small snippet for an instance that what it is doing. 更新 :我的解决方案具有大型javascript,并且我为正在执行的实例放置了小片段。 Like in for there are nested ifs` and nested ternary operators too. 就像in中一样,也有嵌套的ifs和嵌套的三元运算符。 Lets give more snippet 让我们提供更多片段

myfunc: function() {
    for(i = 0; i < 10; i++) {
        ($.inArray(questionNumber, questions) > -1) ? ((Ra === "") ? Report= Report+"<tr><td>lakslak</td></tr>" : Report= Report+"<tr><td>lasaaakslak</td></tr>") : return false;
    }
}

The ternary operator is used on expressions, not on statements. 三元运算符用于表达式,而不用于语句。 You cannot put a return inside there - if you need to, use an if statement. 您不能在其中放一个return -如果需要,请使用if语句。

However, in your case can easily move the return outside: 但是,根据您的情况,可以轻松地将return移至外部:

return (6 == i) ? false : true;

Although you'd better do 虽然你最好做

return 6 != i;

For your updated code, I'd suggest to use 对于您更新的代码,我建议使用

myfunc: function(){
    for (var i=0; i<10; i++) {
        if ($.inArray(questionNumber, questions) > -1)
            Report += (Ra==="") ? "<tr><td>lakslak</td></tr>" : "<tr><td>lasaaakslak</td></tr>";
            // or even
            //     += "<tr><td>"+(Ra===""?"lakslak":"lasaaakslak")+"</td></tr>";
        else
            return false;
    }
}

You cannot use a conditional operator to return in one case but not the other, because return is a statement , and the conditional operator's operands are expressions , not statements. 在一种情况下,您不能使用条件运算符返回,而在另一种情况下,则不能使用条件运算符,因为return是一个语句 ,并且条件运算符的操作数是表达式 ,而不是语句。 In JavaScript, you can use an expression where a statement is expected (it becomes an ExpressionStatement ), but not vice-versa. 在JavaScript中,可以在需要语句的地方使用表达式(该语句变为ExpressionStatement ),反之则不能。

You can't return true or false in ternary but you put ternary in an if-else to return true or false. 您无法在三元数中返回true或false,但是您将三元数放入if-else中以返回true或false。 I don't know whether it is good to approach or not but it works. 我不知道采用这种方法是否很好,但是它可以工作。

if(condition ? value_if_true : null)
{
   return false;
}
else {  
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM