Boo*_*oon 7 javascript template-strings
有没有办法在模板字符串中做条件?
例如:
let x, y;
x = ...
y = ...
let templateString = `${x} ${y}`;
Run Code Online (Sandbox Code Playgroud)
如果y未定义,我不希望输出x之后的模板字符串中的空格.如何使用模板字符串实现这一目标?
这是唯一的方法吗?
let templateString = `${x}${y ? ' ' + y : ''}`;
Run Code Online (Sandbox Code Playgroud)
如果您不在模板中添加逻辑,它看起来会更容易阅读:
let templateString = y ? `${x} ${y}` : `${x}`;
Run Code Online (Sandbox Code Playgroud)
关于什么
let x,y;
const templateString = [x,y].filter(a => a).join(' ');
Run Code Online (Sandbox Code Playgroud)
它首先将你的属性放入数组[].
然后它过滤未定义的项目.
最后一个通过使用join空格创建数组的字符串.
这种方式x或者y可以是未定义的.
从技术上讲,你可以嵌套这些模板字符串,它不漂亮,但这是可行的
let templateString = `${y ? `${x} ${y}`: `${x}`}`;
Run Code Online (Sandbox Code Playgroud)
不过,我会使用第一条评论中的解决方案。
对于这个小例子来说可能有点矫枉过正,但是标记的模板函数提供了一个很好的通用解决方案,它在保持模板字符串干净的同时提供了惊人的灵活性。例如,这里有一个通常会删除未定义变量之前的文本:
function f(str ,...variables){
return variables.reduce((res, v, i) => v ? res + str[i] + v: res, '')
}
let x, y, z;
x = "test"
y = "test2"
// both defined
console.log(f`${x} + ${y}`)
// only one:
console.log(f`${x} + ${z}`)
// random text:
console.log(f`${x} with ${z} and ${y}`)Run Code Online (Sandbox Code Playgroud)
由于它将所有内容传递给函数,因此您几乎可以执行任何您想要的逻辑,同时仍然具有可读字符串。有一些文档关于模板文字的MDN 页面的一半。
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |