Javascript 三元内字符串文字

Javascript 三元内字符串文字,javascript,ecmascript-6,template-literals,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

正在尝试在模板字符串中添加条件。我做不到。我有两个字符串,分别是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、未定义、false等),则可以使用以下代码:

console.log(`${t2?`${t1}(${t2})`:`${t1}`)
这将检查
t2的空值

如果要检查变量的定义,可以使用以下选项:

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

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

console.log(`${t2?`${t1}(${t2})`:`${t1}`)
这将检查
t2的空值

如果要检查变量的定义,可以使用以下选项:

console.log(`${typeof t2!=='undefined'?`${t1}(${t2})`:${t1}`)
让t1=“嘿”;
让t2=“那里”;
console.log(`${t1}${t2?`(${t2})`:'''}`)
t2=零;
console.log(${t1}${t2?`(${t2})`:'''}')
让t1=“嘿”;
让t2=“那里”;
console.log(`${t1}${t2?`(${t2})`:'''}`)
t2=零;

console.log(`${t1}${t2?`(${t2})`:'''}`)
表达式只能在使用字符串文字时写入
{}
内部。您需要在此处使用嵌套模板字符串

让t1=“嘿”;
让t2=“那里”;

console.log(`${t1}${t2?`(${t2})`:'''}`)
表达式只能在使用字符串文字时写入
{}
内部。您需要在此处使用嵌套模板字符串

让t1=“嘿”;
让t2=“那里”;

console.log(`${t1}${t2?`(${t2})`:'''}`)
三元应在
${}
表达式内完成,如下所示:

让t1=“嘿”;
让t2=“那里”;

log(${t1}${t2?`(${t2})`:'''}')
三元应在
${}
表达式内完成,如下所示:

让t1=“嘿”;
让t2=“那里”;

log(${t1}${t2?`(${t2})`:'''}')所以在您的代码中,发生的是,三元运算符也是字符串的一部分,请尝试下面的代码

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

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

在你的代码中,三元运算符也是字符串的一部分,试试下面的代码

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

console.log(t2 ? `${t1}(${t2})` : t1)
两种解决方案:

让t1=“嘿”;
让t2=“那里”;
//当t2存在时,需要像hey(那里)这样的输出。当它为null、未定义或为空时,只显示hey
//已尝试以下方法,但不起作用
log(t2?`${t1}(${t2})`:`(${t1})`)
log(`${t1}${t2&`(${t2})`})
t1=“嘿”;
t2=“”;
log(t2?`${t1}(${t2})`:`${t1}`)
log(${t1}${t2&&`(${t2})`}`)
两种解决方案:

让t1=“嘿”;
让t2=“那里”;
//当t2存在时,需要像hey(那里)这样的输出。当它为null、未定义或为空时,只显示hey
//已尝试以下方法,但不起作用
log(t2?`${t1}(${t2})`:`(${t1})`)
log(`${t1}${t2&`(${t2})`})
t1=“嘿”;
t2=“”;
log(t2?`${t1}(${t2})`:`${t1}`)
console.log(${t1}${t2&&`(${t2})`}`)