首页  >  文章  >  web前端  >  可选链接和空合并

可选链接和空合并

王林
王林原创
2024-08-21 06:13:02693浏览

Optional Chaining and Nullish Coalescing

可选链:优雅的访问器

假设您有一个代表用户的对象,并且您想要访问他们的地址。

过去,你可能做过这样的事情:

const user = {
 name: "Alice",
 address: { street: "123 Main St" }
};

const street = user.address && user.address.street;

console.log('Street: ', street); // Output: 123 Main St

但是如果用户对象没有地址属性或者地址对象没有街道属性会发生什么?

你会得到一个错误!

输入可选链!

此运算符 (?.) 可让您安全地访问嵌套属性,如果链的任何部分丢失,则返回 undefined。

例如:

const user = {
 name: "Bob"
};

const street = user.address?.street;
console.log('Street: ', street); // Output: undefined

看看代码是否干净简洁?

空值合并

默认值捍卫者。

现在,假设您想要为空或未定义的变量分配默认值。传统上,您可能会使用 OR 运算符 (||)。但是,如果变量包含“假”值(例如 0 或空字符串),这可能会导致意外行为。

为什么有用:

  • 它通过替换冗长的 if 语句或三元运算符来简化代码。
  • 它特别关注 null 和 undefined,与逻辑 OR 运算符 (||) 不同,后者也将假值(如 0 或空字符串)视为“缺失”。
let userSettings = null; // Imagine this comes from an API or user input

// Without nullish coalescing:
let theme = userSettings !== null && userSettings !== undefined ? userSettings.theme : 'light';

// With nullish coalescing:
let theme = userSettings?.theme ?? 'light'; // If userSettings.theme is null or undefined, 'light' is used

要点:

  • 左侧??首先评估。
  • 如果左侧为 null 或未定义,则返回右侧。
  • 否则,返回左侧。

在处理可选属性或可能丢失的数据时特别方便。


可选链接和空值合并可帮助您编写更具可读性、健壮性和抗错误性的代码。

以上是可选链接和空合并的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn