javascript - 关于JS三目运算符问题
天蓬老师
天蓬老师 2017-05-19 10:17:40
0
3
581

在三目运算符中使用字符串连接符为什么在条件改变时结果却不变?

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

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

但是,去掉三目运算符前的字符串连接符及字符串就恢复正常了

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

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

求解?

天蓬老师
天蓬老师

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

全部回复(3)
曾经蜡笔没有小新

首先:
什么是三目运算符?
{1} ? {2} : {3} ;
JS引擎首先执行 Boolean({1}) 如果为 True 则返回 {2}False则返回{3}
然后:
"she is "+true === "she is true" //严格相等
所以
Boolean("she is "+true) === Boolean("she is true") // 等于 True
Boolean("she is "+false) === Boolean("she is false") // 也等于 True


但是:
false? "?":"nt"+" here." 中的false是布尔值.
所以Boolean(false) === false
所以Boolean(true) === true

小葫芦

这是一个运算符优先级问题. 首先+(字符串连接运算符)优先级比?:(三目运算符)优先级高,所以运算符优先级问题. 首先+(字符串连接运算符)优先级比?:(三目运算符)优先级高,所以先执行+运算符.
所以两种情况下,分别得到"she is "+true"she is "+false.
再执行三目元算符,但是"she is "+true"she is "+false(String,除了"")转换成Boolean均为true. 所以三目运算符条件为真,所以得到结果为"?"先执行+运算符.
所以两种情况下,分别得到"she is "+true"she is "+false.

再执行三目元算符,但是"she is "+true"she is "+false(String,除了"")转换成Boolean均为true. 所以三目运算符条件为真,所以得到结果为"?".🎜
我想大声告诉你

雷雷 雷雷

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!