字符串文字中的三元

Ternary inside string 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}`)

如果您只是检查变量的 falsy 值(null、undefined、false,...),您可以使用以下代码:

console.log(`${t2 ? `${t1}(${t2})` : `${t1}`}`)

这将检查 t2 的空值。

如果你想检查变量的定义,你可以使用这个:

console.log(`${typeof t2 !== 'undefined' ? `${t1}(${t2})` : `${t1}`}`)

let t1= "hey";
let t2 = "there";

console.log(`${t1}${t2 ? `(${t2})` : ''}`)

t2 = null;

console.log(`${t1}${t2 ? `(${t2})` : ''}`)

使用字符串文字时,只能在{}内写入表达式。您需要在此处使用嵌套模板字符串

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

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

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

以上代码解释如下:

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

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

请注意,您可以在模板文字中包含模板文字。有关详细信息,请参阅 MDN 上的 Template Literals documentation

所以在您的代码中,三元运算符也是字符串的一部分,请尝试以下代码。

let t1= "hey";
let t2 = "";

console.log(t2 ? `${t1}(${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} (${t2})`: `(${t1})`)
console.log(`${t1} ${t2 && `(${t2})`}`)


t1= "hey";
t2 = "";

console.log(t2 ? `${t1} (${t2})`: `${t1}`)
console.log(`${t1} ${t2 && `(${t2})`}`)