在javascript中使用三元运算符连接字符串 [英] Concatenate string with ternary operator in javascript
本文介绍了在javascript中使用三元运算符连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
令人讨厌
以下代码:
var arrays = [1,2,3];
alert('Array has ' + (arrays.length > 0) ? 'multiple':'single' + ' value');
警告为多个
其中string为<强烈的>没有连接与三元结果。
alerts as the multiple
where string is not concatenated with the ternary result.
但是这段代码:
var arrays = [1,2,3];
alert('Array has ' + ((arrays.length > 0) ? 'multiple':'single') + ' value');
提醒数组有多个值
其中字符串与三元结果连接。
alerts as the Array has multiple value
where string is concatenated with the ternary result.
我的问题是:
- 为什么第一个代码没有与字符串连接。
- 第一个代码中是否有语法错误,如果是这样,为什么它不会引发错误。
推荐答案
您的第一个示例以这种方式解析
Your first example is parsed this way
alert(('Array has ' + (arrays.length > 0)) ? 'multiple':('single' + ' value'));
给出 + 的docs / Web / JavaScript / Reference / Operators / Operator_Precedence>运算符优先级远远高于?:
。
given the operator precedence of +
is much higher than that of ?:
.
这篇关于在javascript中使用三元运算符连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文