javascript - Questions about JS ternary operator
天蓬老师
天蓬老师 2017-05-19 10:17:40
0
3
615

Why does the result remain unchanged when the conditions change when using the string concatenation operator in the ternary operator?

        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?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
曾经蜡笔没有小新

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 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 and "she is "+false.

Execute the ternary operator again, but "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 "?".🎜
我想大声告诉你
var notice = "she is "+(true? "?":"nt")+" here."
        alert(notice);    // "?"
var notice = "she is "+(false? "?":"nt")+" here."
        alert(notice);    // "?"
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template