【问题标题】:Null coalescing operator angular 2空值合并运算符 angular 2
【发布时间】:2017-09-04 01:14:41
【问题描述】:

angular 2 中空合并运算符 (??) 的等价物是什么?

在 C# 中我们可以执行这个操作:

string str = name ?? FirstName ?? "First Name is null";

【问题讨论】:

  • 将 OP 的示例修复为正确的 C#。

标签: angular typescript null-coalescing-operator


【解决方案1】:

在打字稿中

Typescript 在3.7 版本中引入了空值合并,因此如果您在3.7 或更高版本上运行,您可以简单地编写:

const str = name ?? firstName ?? "Name and First Name are both null";
const x = foo?.bar.baz() ?? bizz();

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

在 Angular 模板中

从 Angular 12 开始,您还可以在模板中使用 ??

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      也许你想要实现的是:

      let str =
          typeof (name) !== 'undefined' && name !== null ?
              name : typeof (FirstName ) === 'undefined' || FirstName  === null ?
              "First Name is null" : FirstName 
      

      【讨论】:

      • 如果 nameFirstName 字段是空字符串,尽管它们都不为空,但它会导致 First Name is null
      【解决方案4】:

      通过|| 操作符执行合并,即

      let str:string = name || FirstName || "name is null and FirstName is null";
      

      您也可以阅读this question 了解更多详情和解释。

      【讨论】:

      • 或 operator(||) 与 nullish 合并不完全相同。例如:"" || “易卜拉欣”返回“易卜拉欣”和 0 || “易卜拉欣”再次返回“易卜拉欣”。但是合并第一个操作返回“”,第二个返回 0。因为空值合并只控制左侧值是等于 null 还是 undefined
      • 当心 - 这不是空合并运算符,因为 false || true 返回 true
      • 对于任何认为这无关紧要的人,因为 nameFirstName 变量很可能是 strings,请考虑 JavaScript 和 TypeScript 如何处理空字符串。如果nameFirstName 字段为空字符串,则尽管它们都不为空,但将导致name is null and First Name is null
      猜你喜欢
      • 2021-04-20
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 2010-10-13
      • 2018-05-24
      • 2021-06-03
      • 2021-08-29
      相关资源
      最近更新 更多