[英]Best practice conditional variable assignment in typescript
一个非常简单的 typescript 问题,我需要帮助
如果不使用 if 语句,我将如何有条件地将某些内容分配给常量变量
const myConstant = myProduct.productId;
我想要这样,如果 myProduct 中的 productId 为空(“”),它将 myConstant 的变量分配给“No Product”,我希望在不使用 if 语句的情况下执行此操作。
谢谢
我将如何 go 这样做。
这就是你可以做到的...
const myConstant = myProduct.productId || 'No Product';
另外,如果您还想对myProduct
进行null
检查,您可以输入?
为此,如下所示
const myConstant = myProduct?.productId || 'No Product';
PS:这适用于空字符串null
, undefined
和0
。
这将帮助您:
const myConstant = myProduct.productId || 'No Product';
这在 JavaScript 中称为短路评估
在此处阅读更多信息: https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c
您可以尝试以下方法:
const myConstant = myProduct?.productId || 'No Product';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.