search

Home  >  Q&A  >  body text

javascript - Questions about JS ternary operator

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?

天蓬老师天蓬老师2778 days ago660

reply all(3)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新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

    reply
    0
  • 高洛峰

    高洛峰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.

    Execute the ternary operator again, but "she is "+true and "she is "+false(String, except "") converted into Boolean are all true. So the condition of the ternary operator is true, so the result is "?".🎜

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:19:40

    var notice = "she is "+(true? "?":"nt")+" here."
            alert(notice);    // "?"
    var notice = "she is "+(false? "?":"nt")+" here."
            alert(notice);    // "?"

    reply
    0
  • Cancelreply