繁体   English   中英

js switch语句的奇怪行为评估为true / false

[英]Strange behaviour of js switch statement evaluating true/false

我打算使用与下面的实验函数(testIfFalsy)中的语句相似的switch语句,我编写该语句来测试这种switch语句如何评估我希望抛出的某些数值的“真实性”或“虚假性”在它。 我知道这种形式的switch语句“ switch(true)”在某种程度上是不合常规的,但它并不是对switch的非法使用,因此对于代码的可读性和期望使用的数据类型都非常可取它。 以前,我已经非常成功地使用BASIC的case语句完成了同样的事情,现在我将相同的源代码移植到Javascript中。

每个switch的“ case”子句中的注释列出了该子句捕获的值。 我从这段代码中得到了一些意想不到的结果。 首先,当我编写它时,我从没想到会看到“默认”子句捕获到的值,因为那将意味着它们滑过了前面的两个case子句,因此被解释为既不是true也不是false! 但是,正如评论所示,确实存在这样的价值。

所有最奇怪的结果是如何处理数字文字1​​。 “ if(a)”条件在变量a的值为数字1时将其视为true,如该代码中在switch语句之前执行的警告说“ a is true”所表明的那样。 此外,该开关的“默认”子句中的第二个警报显示“ true”,表明语句“ Boolean(a)”也将数值1视为true。 那么,为什么此switch语句既不将其视为true也不是false?

function myCallingFunction() {
   var R;
   // unrelated code ...
   // Tail end of calling function
   R = testIfFalsy(0);
}

function testIfFalsy(a) {
   if (a) {alert ("a is true");}
   switch (true) {
   case (!a):
            alert ("it's true that a is false, a=" + a);
     // when arg is: NaN, undefined, null, 0, -0, 0/0, false,   !1 , '', R
     // value shown= NaN, undefined, null, 0,  0, NaN, false, false,   , undefined
        break;
   case  (a):
            alert ("it's true that a is true. a=" + a);
     // when arg is: true, !0,
     // value shown= true, true,
        break;
   default:
            alert ("a is neither true nor false, a=" + a);
            alert (Boolean(a));
     // when arg is: 1,2,-1,-2, 'cat', 'NaN', [0], 
     // value shown= 1,2,-1,-2,  cat ,  NaN ,  0 ,
   }
}

虽然我不确定,但原因似乎是开关没有执行隐式强制。 Boolean()也可能被视为显式的,因为它被编写为接受布尔值以外的值。 同样,我不确定,但是快速提琴可能会证实这一怀疑。

暂无
暂无

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

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