繁体   English   中英

为什么是?真:'假'? “真”返回“真”?

[英]Why is !true ? 'false' : 'true' returning 'true'?

为什么当我这样做时

(!true) ? 'false' : 'true'

它返回'true'

它只是意味着

if (!true) {
  return 'false';
} else {
  return 'true';
}

!true (不正确)表示false ,因此返回else

A? B: C A? B: C表示如果 A 为 TRUE,则返回值 B。否则返回值 C。由于 A 为FALSE ,它返回恰好为true的值 C。

因为(!true)为 false,所以选择了:的右侧。

因为上面等价于:

if (false) {
    return 'false';
} else {
    return 'true';
}

尽管混淆可能来自以下两者之间的区别:

if (false) // which is false

if (false == false) // which is true

这可以扩展为:

if(!true){
   return 'false';
} else {
   return 'true';
}

if(!true)等同于if(!true= true) ,后者等同于if(false=true) ,即false 因此return (true)位于if语句的 false 一侧。

由于使用字符串文字来表示布尔值,所以混淆就在这里。 如果你颠倒'false''true' ,它更有意义:

(?true): 'true' : 'false'

将返回字符串文字false ,这与boolean值有很大不同。

您的原始陈述(?true): 'false' : 'true'读作

“如果不为真,则返回字符串文字为真”。

我首先发布的声明是

“如果不为真,则返回字符串文字为假”。

其中,如果您知道true的相反()值是false ,那么它就解释了所说明的逻辑。

 const test = true; // change this value to see the result change if (.test) { // if test is NOT truthy console.log('false') } else { // if test === true console.log('true') }

// Since in the original question a ternary expression was used, the above code is equivalent to this:

!test ? console.log('false') : console.log('true');

暂无
暂无

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

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