字符串文字内的三元

v21*_*103 8 javascript ecmascript-6 template-literals

一直尝试在模板字符串中添加条件。我做不到。我有两个字符串,即 t1 和 t2,当 t2 未定义或为空时,仅显示 t1,当 t2 存在时,将 t2 与 t1 一起附加在括号内

let t1= "hey";
let t2 = "there";
//need the output something like hey(there) when there t2 is present. when it is null or undefined or empty just show hey 

//Have tried the below but it is not working
console.log(`${t2} ${t1} ? ${t1}(${t2}): ${t1}`)
Run Code Online (Sandbox Code Playgroud)

Edr*_*ric 9

三元应该在表达式内部完成,${}如下所示:

let t1 = "hey";
let t2 = "there";
console.log(`${t1}${t2 ? `(${t2})` : ''}`);
Run Code Online (Sandbox Code Playgroud)

上面代码的解释如下:

  1. hey由于您已指定无论是否定义都应指定前缀“ ” t2,因此无需将其包含在三元表达式中。
  2. 代码的下一部分是一个内联三元运算符,用于检查是否t2true

    • 如果为真,则执行三元运算符的第一部分。换句话说,三元运算符将返回(${t2})。由于这是另一个模板文字,因此将通过将变量替换t2到模板表达式中来对其进行评估。
    • 如果不为真,则执行三元运算符的第二部分,它是一个空字符串。

请注意,您可以在模板文字中包含模板文字。有关更多信息,请参阅MDN 上的模板文字文档。