【发布时间】:2017-09-04 01:14:41
【问题描述】:
angular 2 中空合并运算符 (??) 的等价物是什么?
在 C# 中我们可以执行这个操作:
string str = name ?? FirstName ?? "First Name is null";
【问题讨论】:
-
将 OP 的示例修复为正确的 C#。
标签: angular typescript null-coalescing-operator
angular 2 中空合并运算符 (??) 的等价物是什么?
在 C# 中我们可以执行这个操作:
string str = name ?? FirstName ?? "First Name is null";
【问题讨论】:
标签: angular typescript null-coalescing-operator
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 12 开始,您还可以在模板中使用 ??。
【讨论】:
该运算符是在 TypeScript 3.7 中添加的 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
【讨论】:
也许你想要实现的是:
let str =
typeof (name) !== 'undefined' && name !== null ?
name : typeof (FirstName ) === 'undefined' || FirstName === null ?
"First Name is null" : FirstName
【讨论】:
name 和 FirstName 字段是空字符串,尽管它们都不为空,但它会导致 First Name is null。
通过|| 操作符执行合并,即
let str:string = name || FirstName || "name is null and FirstName is null";
您也可以阅读this question 了解更多详情和解释。
【讨论】:
false || true 返回 true。
name 和 FirstName 变量很可能是 strings,请考虑 JavaScript 和 TypeScript 如何处理空字符串。如果name 和FirstName 字段为空字符串,则尽管它们都不为空,但将导致name is null and First Name is null。