Javascript 为什么是 !true ?“假”:“真”返回“真”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5591139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is !true ? 'false' : 'true' returning 'true'?
提问by JM at Work
Why is it that when I do
为什么我这样做的时候
(!true) ? 'false' : 'true'
it returns 'true'
?
它返回'true'
?
回答by Buhake Sindi
It simply means
简单来说就是
if (!true) {
return 'false';
} else {
return 'true';
}
!true
(not true) means false
, so the else
is returned.
!true
(not true) 表示false
,因此else
返回 。
回答by Buhake Sindi
The syntax of A ? B : C
means that if A is TRUE, then return the value B. Else return value C. Since A is FALSE
, it returns the value C which happens to be true
.
的语法A ? B : C
意味着如果 A 为 TRUE,则返回值 B。否则返回值 C。由于 A 是FALSE
,它返回值 C 恰好是true
。
回答by Daniel
Because (!true)
is false, and then the right side of the :
is chosen.
因为(!true)
是假的,然后选择右边的:
。
回答by David Tang
Because the above is equivalent to:
因为上面的等价于:
if (false) {
return 'false';
} else {
return 'true';
}
Though perhaps the confusion is coming from the difference between:
虽然可能混淆来自以下之间的差异:
if (false) // which is false
And
和
if (false == false) // which is true
回答by StKiller
This can be expanded to:
这可以扩展为:
if(!true){
return 'false';
} else {
return 'true';
}
回答by ndabenhle
if(!true)
is equivalent to if(!true= true)
which is equivalent to if(false=true)
which is false
. Therefore return (true)
which is on the false side of the if
statement.
if(!true)
相当于if(!true= true)
哪个相当于if(false=true)
哪个是false
。因此return (true)
,这是if
陈述错误的一面。
回答by Brian
The confusion lies here because of the use of string literals to represent boolean values. If you reverse the 'false'
and 'true'
, it makes more sense:
由于使用字符串文字来表示布尔值,因此存在混淆。如果你反转'false'
and 'true'
,它更有意义:
(!true) ? 'true' : 'false'
(!true) ? 'true' : 'false'
Would return the string literal false
, which is much different than a boolean
value.
将返回字符串文字false
,这与boolean
值大不相同。
Your original statement (!true) ? 'false' : 'true'
reads as
你的原始声明(!true) ? 'false' : 'true'
读作
"If not true, then return the string literal true".
“如果不为真,则返回字符串文字为真”。
The statement I posted first reads as
我首先发布的声明读作
"If not true, then return the string literal false".
“如果不为真,则返回字符串文字假”。
Which, if you know the opposite (not) value of trueis false, then it explains the logic illustrated.
其中,如果您知道true的相反(非)值是false,那么它解释了所说明的逻辑。
回答by Dzenis H.
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');