javascript:nullish联合运算符介绍及实例

128 阅读2分钟

nullish凝聚运算符是在最新的javascript中引入的逻辑运算符,即EcmaScript 2020。

这篇文章介绍了什么是javascript/typescript中的nullish凝聚运算符,以及它是如何在Angular 12组件中使用的。

nullish联合运算符是一个逻辑运算符,用于检查两个值是否为空或未定义。

nullish缩写为参数的空值和未定义值,coalescing是指合并两个值。

下面是一个语法

firstvalue ?? second value

双重问号是null联合运算符的一个符号。

如果第一个值为空或未定义,返回第二个值,如果第二个值为空或未定义,返回第一个值。

下面是一个例子

const output = null ?? '123';
console.log(output); // 123

const output1 = 11 ?? 0;
console.log(output1); //11

同样的操作符集成在Angular 12中,并在2021年发布。

?double quotation ,作为Angular 12语言的一部分引入。

这将在Angular typescript组件以及html模板中使用。

Angular 12中的双引号运算符在typecript组件中的应用

在Angular 12之前,我们必须写下面的代码来检查空或未定义。

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message = undefined;
  getMessage() {
    if (this.message !== null && this.message !== undefined) {
      return "default message";
    }
    return this.message;
  }
}

有了Angular 12,我们可以简化null和undefined的检查,并在typescript组件中写出简洁的代码。

下面是操作符在组件中的用法

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  message = undefined;
  getMessage() {
       return this.message ?? 'Default message';

  }
}

html模板中的Angular 12双引号运算符

在html模板组件中,app.component.html

{{message !== null && message !== undefined ? message : "default message" }}

在Angular12中,更清洁的方法是

{{message ?? "default message" }}

这个无效操作符适用于所有数据类型值的typescript

  • 数字
  • 字符串
  • 布尔
  • 对象

总结

这有助于在编写Angular组件时写出干净简单的代码,虽然一开始有点难学。

它可以帮助程序员写出好的代码。