使用模板文字检查两个条件

时间:2019-08-05 18:00:19

标签: javascript template-literals

我在对象中有以下代码行:

return {
    subtitle: `Published ${date} by ${author}`
}

这是事实,不一定要设置dateauthor-这意味着我想根据是否{{1}来有条件地渲染subtitle },或者date,或者两者都设置。

现在,如果我只需要担心日期,那么我可以进行以下检查:

author

那行得通。

同样,对于作者:

return {
    subtitle: date && `Published ${date}`
}

我不知道如何同时检查日期和作者。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为您是要像这样进行条件检查?

return date && author ? { subtitle: `Published ${date} by ${author}` }
    : date && !author ? { subtitle: `Published ${date}` }
    : !date && author ? { subtitle: `by ${author}` }

答案 1 :(得分:0)

假设subtitledate均为空时可以将author设置为空字符串,那么我认为有必要使用tagged template

  

模板文字的更高级形式是带标签的模板。标签允许您使用函数来解析模板文字。标记函数的第一个参数包含一个字符串值数组。其余参数与表达式相关。最后,您的函数可以返回您操作的字符串[...]

在我看来,这将使两全其美。在抽象化字符串处理的繁琐细节时,您可以保持Published ${date} by ${author}的表现力和简单性。

它看起来像这样:

subtitle`Published ${date} by ${author}`
//=> 'Published 2019 by John'
//=> or 'Published 2019'
//=> or 'by John'
//=> or ''

注意::为简单起见,我使用了flatMap,但是除非您将其填充,否则此代码在IE / Edge中将不起作用。

const subtitle = (strings, date, author) =>
  strings
    .flatMap((str, idx) =>
      idx === 0 && date ? [str, date] :
      idx === 1 && author ? [str, author] :
      [])
    .join('')
    .trim();
    
let date;
let author;

date = '2019', author = 'John';
console.log( subtitle`Published ${date} by ${author}` );

date = '2019', author = '';
console.log( subtitle`Published ${date} by ${author}` );

date = '', author = 'John';
console.log( subtitle`Published ${date} by ${author}` );

date = '', author = '';
console.log( subtitle`Published ${date} by ${author}` );