[英]Can we use JS concat() inside Template literals (Template strings)?
I am trying to create a URL using Template Strings like -我正在尝试使用模板字符串创建一个 URL,例如 -
a = {
link: {
pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
},
};
The above snippet is working absolutely fine so is the below one.上面的代码片段工作得非常好,下面的代码片段也是如此。 But should we use concat() inside Template strings like the below snippet or not?但是我们是否应该在模板字符串中使用 concat() 像下面的代码片段一样?
a = {
link: {
pathname: `${url
.split('?')[0]
.concat(`${userId}/items?userType=${userId}`)}`,
},
};
Why I used concat() because in my case, my enabled linting setup is throwing error for the first one as it should be written in two-lines, but it takes a new line or space as we give, which is not favorable in our case as we are creating URL.为什么我使用 concat() 是因为在我的情况下,我启用的 linting 设置会抛出第一个错误,因为它应该写成两行,但它需要一个新的行或空格,这在我们的情况下是不利的案例,因为我们正在创建 URL。
If not, why?如果不是,为什么? Just Curious.只是好奇。
Two answers for you:给你两个答案:
The content of a substitution ( ${...}
) can be any expression.替换 ( ${...}
) 的内容可以是任何表达式。 It's fine to do method calls there.可以在那里进行方法调用。
concat
seems like an odd choice in that particular case, since there's no need for it.在这种特殊情况下, concat
似乎是一个奇怪的选择,因为不需要它。 For that reason, from a style perspective, I'd use the first version.出于这个原因,从风格的角度来看,我会使用第一个版本。 But it's a style thing, and you can use concat
if you like.但这是一种风格,如果您愿意,可以使用concat
。 Note VLAZ's point that once you've done that, the whole expression is already producing the string you want and you have no need of a template literal at all.请注意VLAZ 的观点,一旦你这样做了,整个表达式就已经产生了你想要的字符串,你根本不需要模板文字。
So I'd either use your original:所以我要么使用你的原件:
a = {
link: {
pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
},
};
or if you prefer concat
:或者如果您更喜欢concat
:
a = {
link: {
pathname: url
.split('?')[0]
.concat(`${userId}/items?userType=${userId}`)},
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.