在模板文字中使用条件 [英] Using conditionals inside template literals

查看:51
本文介绍了在模板文字中使用条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道还有更优雅的方法来定义包含变量的字符串, 但是如果我想在ES6之前的版本中添加条件,那就可以了.

I know there are more elegant ways to define a string with variables included, but if I want to add a conditional in pre ES6 I would do..

var a = "text"+(conditional?a:b)+" more text"

现在我可以使用模板文字了.

now with template literals I would do..

   let a;
   if(conditional) a = `test${a} more text`;
   else a = `test${b} more text`;

是否有更优雅的方法来实现此条件?是否可以包含快捷方式?

Is there a more elegant way to implement this conditional? is it possible to include if shortcut?

推荐答案

使用此:

let a = `test${conditional ? a : b} more text`;

这篇关于在模板文字中使用条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆