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?
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
This is a
Execute the ternary operator again, butoperator 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 and
"she is "+false
."she is "+true
and"she is "+false
(String
, except""
) converted intoBoolean
are alltrue code>. So the condition of the ternary operator is true, so the result is
"?"
.🎜