2 回答
TA贡献1811条经验 获得超4个赞
我想你的意思是做这样的条件检查?
return date && author ? { subtitle: `Published ${date} by ${author}` } : date && !author ? { subtitle: `Published ${date}` } : !date && author ? { subtitle: `by ${author}` }
TA贡献1876条经验 获得超5个赞
假设subtitle可以被设置为如果两个空字符串date和author为空的话,我认为有一种使用的情况下,标签的模板:
模板文字的更高级形式是标记模板。标签允许您使用函数解析模板文字。标签函数的第一个参数包含一个字符串值数组。其余参数与表达式相关。最后,您的函数可以返回您操纵的字符串[...]
在我看来,这将允许两全其美。您保留了表现力和简单性,Published ${date} by ${author}同时抽象了字符串处理的血腥细节。
它看起来像这样:
subtitle`Published ${date} by ${author}`
//=> 'Published 2019 by John'
//=> or 'Published 2019'
//=> or 'by John'
//=> or ''
注意:flatMap为了简单起见,我使用了此代码,除非您对其进行 polyfill,否则此代码将无法在 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}` );
添加回答
举报