我只是想知道是否有人有更优化、更简洁的方式来做到这一点。
你有这个倒退。更简洁不是更具可读性。一行中的操作越多,就越难弄清楚它的作用:
a ?? b ? c ?? d?.e : f || x
如果不是全部在一行中,则更难从心理上解析。除其他事项外,您需要记住操作的顺序 - OR 是指 (f || x) 还是整个表达式到那里的 OR-ing?
它将被解析为(a ?? b ? c ?? d?.e : f) || x。然而,在你的脑海中评估这一点几乎没有帮助。
更优化和可读的方式是使用常规的if/else 语句
let status;
if (person?.status == null)
status = 'Loading...';
else if (person.status)
status = 'Verified';
else
status = 'Not Verified';
如果需要,可以封装在一个函数中。
function status(person) {
if (person?.status == null)
return 'Loading...';
if (person.status)
return 'Verified';
return 'Not Verified';
}
如果你真的需要一些简短的东西来使用,你可以有一个简单的查找表来解析不同的可能值:
const lookup = {
"null" : 'Loading...',
"true" : 'Verified',
"false": 'Not Verified',
}
/* ... */
const status = lookup[person?.status ?? null];
也可以:删除 nullish 合并运算符并在查找中编码 undefined:
const lookup = {
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
}
/* ... */
const status = lookup[person?.status];
这几乎无关紧要,但有些有趣。您可以结合查找和函数来创建一个相当小的函数,该函数不使用if/else 或switch-es 来确定要返回的内容:
const status = person => ({
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
})[person?.status];
console.log( status() ); //Loading...
console.log( status(null) ); //Loading...
console.log( status({}) ); //Loading...
console.log( status({status: true}) ); //Verified
console.log( status({status: false}) ); //Not Verified
这不是最佳做法,但偶尔会派上用场。它可以帮助制作原型。例如,从函数中提取对象是一个简单的重构,这反过来又允许您从配置中加载它。在这种情况下,如果您有类似的东西,它可能有助于将其翻译成不同的语言
{
'english': {
"null" : 'Loading...',
"undefined" : 'Loading...',
"true" : 'Verified',
"false" : 'Not Verified',
},
'pig-lating': {
"null" : 'Oadinglay...',
"undefined" : 'Oadinglay...',
"true" : 'Erifiedvay',
"false" : 'Otnay Erifiedvay',
}
}