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

Check two conditions with a template literal

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

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

事情是这样的,不一定会设置 dateauthor - 这意味着我想根据是否 [=] 有条件地呈现 subtitle 13=] 已设置,author 已设置或两者都已设置。

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

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

那行得通。

同样,作者:

return {
    subtitle: author && `by ${author}`
}

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

知道怎么做吗?

我想你的意思是像这样进行条件检查?

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

假设如果 dateauthor 都为空,则 subtitle 可以设置为空字符串,那么我认为有使用 tagged template 的情况:

A more advanced form of template literals are tagged templates. Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions. In the end, your function can return your manipulated string[...]

在我看来,这将允许两全其美。您保留了 Published ${date} by ${author} 的表现力和简单性,同时抽象掉了字符串处理的血腥细节。

看起来像这样:

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

注意: 为了简单起见,我使用了 flatMap,但这段代码在 IE/Edge 中不起作用,除非你对其进行 polyfill。

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}` );