[英]Is there any way of determining which or statement is true in javascript?
所以说我有一个if声明:
if(a=='' || b==''){
//which is true?
}
是否可以确定哪个语句满足if语句而不执行switch
语句或另一个if
语句来检查?
正如其他人所说,你必须分别测试条件,但你可以混合世界。
var test1 = 1 == 1; // true
var test2 = 2 == 1; // false
if (test1 || test2) {
// If either conditions is true, we end up here.
// Do the common stuff
if (test1) {
// Handle test1 true
}
if (test2) {
// Handle test2 true
}
}
您可以定义令牌以存储条件为真:
var token = null;
if ((a == '' && (token = 'a')) || (b == '' && (token = 'b'))) {
// Here token has an 'a' or a 'b'. You can use numbers instead of letters
}
我认为这是做你想做的最简单的方法。
不,您已明确询问其中一个或两个是否属实。 没有其他某种条件,没有办法弄清楚哪些子表达式是真的。
如果你对基于哪种行为的不同行为感兴趣,你应该将它们与可能常见的位分开,例如
either = false;
if (a == ' ') {
doActionsForA();
either = true;
}
if (b == ' ') {
doActionsForB();
either = true;
}
if (either) {
doActionsForAorB();
}
如果你关心这两个条件中的哪一个是真的,唯一的方法就是分别测试它们,例如
if(a==''){
// ...
}
else if(b=='') {
// ...
}
有时,特别是在更复杂的条件中,如果您存储每个条件的结果并在以后重复使用它会有所帮助:
var isFoo = a == '';
var isBar = b == '';
// You can now use isFoo and isBar whenever it's convenient
简单的解决方案:
if ((ia=(a=='')) || (b=='')) {
// ia indicate whether the boolean expression a have been true.
// ia -> a has been true, b may have, !ia -> b has been true, a has not
}
在简单的解决方案中没有ib
,因为它不会总是由于快捷方式评估而设置。
为迎合捷径评估尝试:
if (((ia=(a=='') || (ib=(b=='')) && ((ib=(b=='')) || (ia=(a==''))) {
// ia, ib indicate whether the corresponding boolean expressions have been true
}
if(a ==''|| b ==''){var x = a ||
b;
//如果a是''(falsy)x将是b,否则a
}
var phone="";
var email="something";
if(phone=='' || email==''){
var x= (phone) ? 'phone':'email';
console.log(x); //email
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.