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); // "?"
求解?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
首先:
什么是三目运算符?
{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. 所以三目运算符条件为真,所以得到结果为"?".