简体   繁体   English

如何避免三元未定义和 boolean 检查?

[英]how to avoid ternary for undefined and boolean check?

From this,由此,

{[item.name]: item.value?== undefined. item:value : ''}

when value is,,, it must be当值是,,,它必须是

false -> {[item.name]: false}
true -> {[item.name]: true}
'str' -> {[item.name]: 'str'}
undefined -> {[item.name]: ''}

How do I avoid the ternary operator?如何避免三元运算符?

item.value !== undefined ? item.value : ''

item.value | '' item.value | '' fails because when value is false , it sets '' instead. item.value | ''失败,因为当 value 为false时,它会设置''

For modern browsers ( not IE ) there exist the Nullish coalescing operator ??对于现代浏览器(不是 IE ),存在Nullish 合并运算符?? which returns the right-hand side only when the left-hand is null or undefined .仅当左侧为nullundefined时才返回右侧。

So you can do所以你可以做

{[item.name]: item.value ?? ''}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM