【问题标题】:Best practice conditional variable assignment in typescript打字稿中的最佳实践条件变量赋值
【发布时间】:2021-11-23 05:25:08
【问题描述】:

一个非常简单的打字问题,我需要帮助

如果不使用 if 语句,我如何有条件地为常量变量赋值

const myConstant = myProduct.productId;

我希望如果 myProduct 中的 productId 为空 (""),它会将 myConstant 的变量分配给“No Product”,我希望不使用 if 语句来执行此操作。

谢谢

我该怎么做呢。

【问题讨论】:

    标签: javascript typescript conditional-statements


    【解决方案1】:

    这就是你可以做到的......

    const myConstant = myProduct.productId || 'No Product';
    

    另外,如果你也想做null 检查myProduct,你可以输入?,如下所示

    const myConstant = myProduct?.productId || 'No Product';
    

    PS:这适用于空字符串、nullundefined0

    【讨论】:

      【解决方案2】:

      这将对您有所帮助:

      const myConstant = myProduct.productId || 'No Product';
      

      这在 JavaScript 中称为短路评估

      在此处阅读更多信息:https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c

      【讨论】:

        【解决方案3】:

        你可以试试这样的:

        const myConstant = myProduct?.productId || 'No Product';

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-26
          • 1970-01-01
          • 2016-05-14
          • 2022-06-15
          相关资源
          最近更新 更多