碎片时间学编程「133]:如何在 JS 项目中使用可选链接和无效合并?


JavaScript ES2020 引入了一些新特性来帮助我们编写更简洁的代码。让我们快速浏览一下它们中的两个,它们旨在使对象和变量的工作变得更加容易。

可选链接

可选的链接运算符( ?.) 允许我们访问深度嵌套的对象属性,而无需验证嵌套链中的每个引用。如果引用为空(nullundefined),则可选链接运算符将短路,返回undefined. 可选的链接运算符也可以与函数调用一起使用,如果给定的函数不存在则返回 undefined。

生成的代码更短更简单,如下所示:

JavaScript

const data = getDataFromMyAPI();

// Without optional chaining
const userName = data && data.user && data.user.name;
const userType = data && data.user && data.user.type;
data && data.showNotifications && data.showNotifications();

// With optional chaining
const userName = data?.user?.name;
const userType = data?.user?.type;
data.showNotifications?.();

无效合并

同样,空值合并运算符( ??) 是一个逻辑运算符,它允许我们检查空值 (nullundefined),当值非空值时返回右侧操作数,否则返回左侧操作数.

除了更简洁的代码之外,这个运算符可能会让我们免于与虚假值相关的一些麻烦:

const config = getServerConfig();

// 没有无效的合并
const port = config.server.port || 8888;
// 即使我们将其传递为假,这也是正确的
const wrongkeepAlive = config.server.keepAlive || true;
// 我们必须明确检查无效值
const keepAlive =
  (config.server.keepAlive !== null & config.server.keepAlive !== undefined)
  ? config.server.keepAlive : true;

// 具有无效合并
const port = config.server.port ?? 8888;
// 这工作正常
const keepAlive = config.server.keepAlive ?? true;

注意:请记住,这两个功能都是相当新的,因此它们的支持可能还不是很好。

更多内容请访问我的网站:https://www.icoderoad.com

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章