var notice = "she is "+true? "?":"nt"+" here."
alert(notice); // "?"
var notice = "she is "+false? "?":"nt"+" here."
alert(notice); // "?"
However, removing the string concatenator and string before the ternary operator returns to normal
var notice = false? "?":"nt"+" here."
alert(notice); // "nt here."
var notice = true? "?":"nt"+" here."
alert(notice); // "?"
Solution?
曾经蜡笔没有小新2017-05-19 10:19:40
First:
What is the ternary operator?
{1} ? {2} : {3} ;
JS engine executes first Boolean({1})
如果为 True
则返回 {2}
,False
则返回{3}
then:
"she is "+true === "she is true" //strictly equal
so
Boolean( "she is "+true) === Boolean("she is true") // Equal to True
Boolean("she is "+false) === Boolean("she is false") // Also equal to True
But: false in false? "?":"nt"+" here."
is a Boolean value.
So Boolean(false) === false
So Boolean(true) === true
高洛峰2017-05-19 10:19:40
This is a operator priority issue
. First of all, +
(string concatenation operator) has a higher priority than ?:
(Ternary operator) has high priority, so 运算符优先级问题
. 首先+
(字符串连接运算符)优先级比?:
(三目运算符)优先级高,所以先执行+
运算符.
所以两种情况下,分别得到"she is "+true
和"she is "+false
.
再执行三目元算符,但是"she is "+true
和"she is "+false
(String
,除了""
)转换成Boolean
均为true
. 所以三目运算符条件为真,所以得到结果为"?"
executes the +
operator first.
So in the two cases, we get "she is "+true< /code> and
"she is "+false
.
"she is "+true
and "she is "+false
(String
, except ""
) converted into Boolean
are all true code>. So the condition of the ternary operator is true, so the result is "?"
.🎜reply0
我想大声告诉你2017-05-19 10:19:40
var notice = "she is "+(true? "?":"nt")+" here."
alert(notice); // "?"
var notice = "she is "+(false? "?":"nt")+" here."
alert(notice); // "?"