我们可以在模板文字模板字符串中使用JS concat吗?

问题描述

我正在尝试使用--p的模板字符串创建URL

a = {
    link: {
        pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
    },};

上面的代码段工作正常,下面的代码段也是如此。 但是我们是否应该在模板字符串(如下面的代码片段)中使用concat()?

a = {
    link: {
        pathname: `${url
            .split('?')[0]
            .concat(`${userId}/items?userType=${userId}`)}`,},};

为什么使用concat()是因为在我的情况下,启用的linting设置会为第一个抛出错误,因为它应该用两行写成,但是它需要一个新的行或空格,而不是在我们创建URL的情况下是有利的。

如果没有,为什么? 只是好奇。

解决方法

为您提供两个答案:

  1. 替换(${...})的内容可以是任何表达式。可以在那里进行方法调用。

  2. 在特定情况下,
  3. concat似乎是一个奇怪的选择,因为不需要它。因此,从样式角度来看,我将使用第一个版本。但这是一种风格,您可以可以使用concat。请注意VLAZ's point,一旦完成,整个表达式已经在生成您想要的字符串,并且您根本不需要模板文字。

所以我要么用你的原件:

a = {
    link: {
        pathname: `${url.split('?')[0]}${userId}/items?userType=${userId}}`
    },};

或者如果您更喜欢concat

a = {
    link: {
        pathname: url
            .split('?')[0]
            .concat(`${userId}/items?userType=${userId}`)},},};