javascript - 关于JS三目运算符问题
天蓬老师
天蓬老师 2017-05-19 10:17:40
[JavaScript讨论组]

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

        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. 所以三目运算符条件为真,所以得到结果为"?".

我想大声告诉你
var notice = "she is "+(true? "?":"nt")+" here."
        alert(notice);    // "?"
var notice = "she is "+(false? "?":"nt")+" here."
        alert(notice);    // "?"
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号