Optional Chaining(?.)与 Nullish Coalescing(??):减少代码冗余的底层解析规则

技术讲座:Optional Chaining(?.)与 Nullish Coalescing(??)解析与实战

引言

在现代编程中,处理可能为 nullundefined 的变量是常见场景。为了减少代码冗余和提高代码可读性,JavaScript 提供了 Optional Chaining(?.)和 Nullish Coalescing(??)两种操作符。本文将深入探讨这两种操作符的原理、用法,并通过工程级代码示例展示如何在实际项目中应用它们。

Optional Chaining(?.)

什么是 Optional Chaining?

Optional Chaining 允许你安全地访问嵌套对象或数组的属性,即使某些属性可能不存在。它通过在属性名后添加 ?. 来实现。

原理

当尝试访问一个可能不存在的属性时,如果该属性不存在,Optional Chaining 会返回 undefined 而不是抛出错误。

示例

以下是一个使用 Optional Chaining 的示例:

const user = {
  id: 1,
  profile: {
    name: 'John',
    address: {
      city: 'New York'
    }
  }
};

console.log(user.profile?.address?.city); // 输出: New York
console.log(user.profile?.age); // 输出: undefined

在这个例子中,即使 user.profile.age 不存在,代码也不会抛出错误。

工程级代码示例

以下是一个使用 Optional Chaining 的工程级代码示例:

class User {
  constructor(id, profile) {
    this.id = id;
    this.profile = profile;
  }

  getFullName() {
    return this.profile?.name || 'Unknown';
  }
}

const user = new User(1, { name: 'John' });
console.log(user.getFullName()); // 输出: John

在这个例子中,getFullName 方法使用 Optional Chaining 来安全地访问 user.profile.name

Nullish Coalescing(??)

什么是 Nullish Coalescing?

Nullish Coalescing 是一个条件运算符,当左侧的表达式是 nullundefined 时,它会返回右侧的表达式。它与传统的 || 运算符不同,后者在左侧表达式为 0""NaN 时也会返回右侧的表达式。

原理

Nullish Coalescing 仅在左侧表达式为 nullundefined 时才返回右侧表达式,这意味着它不会对 0""NaN 进行隐式类型转换。

示例

以下是一个使用 Nullish Coalescing 的示例:

let age = null;
console.log(age ?? 18); // 输出: 18
console.log('' ?? 'Empty'); // 输出: 'Empty'

在这个例子中,即使 agenullNullish Coalescing 也会返回 18

工程级代码示例

以下是一个使用 Nullish Coalescing 的工程级代码示例:

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  getPriceWithTax() {
    return this.price ?? 0;
  }
}

const product = new Product(null, 100);
console.log(product.getPriceWithTax()); // 输出: 0

在这个例子中,如果 product.pricenullgetPriceWithTax 方法会返回 0

结合使用 Optional Chaining 和 Nullish Coalescing

以下是一个结合使用 Optional ChainingNullish Coalescing 的示例:

const user = {
  id: 1,
  profile: {
    name: 'John',
    address: {
      city: 'New York'
    }
  }
};

console.log(user.profile?.address?.city ?? 'Unknown City'); // 输出: New York

在这个例子中,如果 user.profile.address.citynullundefined,代码会返回 'Unknown City'

总结

Optional ChainingNullish Coalescing 是 JavaScript 中非常有用的特性,它们可以帮助我们编写更简洁、更安全的代码。通过本文的讲解和示例,相信你已经对这些特性有了深入的理解。在实际项目中,合理运用这些特性可以大大提高代码的可维护性和可读性。

附录:其他语言的类似特性

虽然本文主要讨论了 JavaScript 中的特性,但其他一些编程语言也提供了类似的概念:

语言 特性 描述
TypeScript Non-null assertion !,用于断言一个变量不是 nullundefined
Python get() 方法 类中可以使用 get() 方法来获取属性值,并提供默认值。
Java 安全空指针检查 使用 NullPointerException 异常来处理空指针。
C# Null-coalescing assignment ??=,用于将右侧表达式的值赋给左侧变量,如果左侧为 null

通过了解这些类似特性,你可以更好地理解不同语言中的安全编程实践。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注