簡體   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