[英]Best practice conditional variable assignment in typescript
A very easy typescript question, which I need assistance with一个非常简单的 typescript 问题,我需要帮助
Without using if statements, how would I conditional assign something to a constant variable如果不使用 if 语句,我将如何有条件地将某些内容分配给常量变量
const myConstant = myProduct.productId;
I want it so that if the productId in myProduct is empty (""), it will assign the variable of myConstant to "No Product", I wish to do this without utilizing if statements.我想要这样,如果 myProduct 中的 productId 为空(“”),它将 myConstant 的变量分配给“No Product”,我希望在不使用 if 语句的情况下执行此操作。
Thanks谢谢
How would I go about doing this.我将如何 go 这样做。
This is how you could do it...这就是你可以做到的...
const myConstant = myProduct.productId || 'No Product';
Also, if you'd like to do null
check for myProduct
as well, you could put ?
另外,如果您还想对myProduct
进行null
检查,您可以输入?
for it, like below为此,如下所示
const myConstant = myProduct?.productId || 'No Product';
PS: this would work with empty strings, null
, undefined
and with 0
. PS:这适用于空字符串null
, undefined
和0
。
This will help you:这将帮助您:
const myConstant = myProduct.productId || 'No Product';
This is called Short Circuit Evalution in JavaScript这在 JavaScript 中称为短路评估
Read more here: https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c在此处阅读更多信息: https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c
You can try something like:您可以尝试以下方法:
const myConstant = myProduct?.productId || 'No Product';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.