我如何找到默认为true的条件

how can I find what condition defaulted to true?

本文关键字:true 条件 默认 何找      更新时间:2023-09-26

在javascript中,我有一个if语句,我想记录默认为true的第一个条件。例如,如果是a === true,那么我想要console.log a(更新:例如,"a"或"b"或"c",实际字符)。

有什么想法吗?

if(a || b || c){ console.log(this) }

谢谢大家!

当然,最好使用调试器,并在分支到if语句体时检查ab和/或c。:-)

在代码中执行,如果您真的想查看"a"、"b"或"c"更新,没有捷径可走。我在想什么?当然有一条捷径:

if(a || b || c){
    console.log(a ? "a" : b ? "b" : "c");
}

或者,如果你也想看到价值:

if(a || b || c){
    console.log(a ? "a: " + a : b ? "b: " + b : "c: " + c);
}

实时示例|实时源


原始较长版本:

if(a || b || c){
    if (a) {
        console.log("a: " + a);
    }
    else if (b) {
        console.log("b: " + b);
    }
    else {
        console.log("c: " + c);
    }
}

或者(这很棘手,要长很多,所以不推荐):

if(a || b || c){
    switch (false) {
        case !a:
            console.log("a: " + a);
            break;
        case !b:
            console.log("b: " + b);
            break;
        default:
            console.log("c: " + c);
    }
}

这是因为switch语句case s是在运行时按顺序求值的。

只是分解成if链。

if(a){
     // a is true, b and c unknown
} else if(b){
     // a is false, b is true, c is unknown
} else if (c){
     // a and b both false, c is true
} else {
     // a b and c all false
}

当然,如果你愿意,你可以添加更多的条件。

if (a) {
   console.log(a);
   console.log(this);
} else if (b) {
   etc...
} else if (c) {
   etc...
} else {
   ... profit?
}

如果你不想写出一个长的if/then/else链,另一种选择是将你想要检查的值填充到一个数组中,在数组上循环,然后在你达到第一个真值时记录/中断。

保存第一个(如果有)true变量,并使用它:

var x = a || b || c ;
if(x){ console.log(x) }

编辑:清除混乱:

var a, b, c;
a = "";
b = null;
c = "12";
var x = a || b || c;
if (x) 
    alert(x);​ // Alerts "12" (and not "true").

Fiddle显示您将获得x的,而不是x是否为真。

通过undercore.js 的另一种方式

console.log(_.chain([a,b,c]).compact().first().value())