迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

什么是 Javascript 中的 Nullish Coalescing(或 ??)

作者:迹忆客 最近更新:2022/08/19 浏览次数:

在 Javascript 中,无效的合并运算符,或 ?? 运算符用于在左侧为 nullundefined 时返回右侧。 为了更好地理解,让我们看几个例子:

// 设置为 0
let x = 0 ?? "hello";

// 设置为 goodbye
let y = undefined ?? "goodbye";

// 设置为 hello
let z = null ?? "hello";

// 设置为 false
let a = false ?? "goodbye";

nullish 合并运算符在可以返回 nullundefined 的情况下很有用,并帮助我们精简代码。 例如,可以为在某些情况下返回 undefined 的函数提供默认值:

let myFunction = (a) => {
    if(a >= 5) {
        return "hello world";
    }
}

// 将返回“goodbye world”,因为 `myFunction(4)` 返回 undefined。
let runFunction = myFunction(4) ?? "goodbye world";

逻辑 OR 运算符之间的差异

过去,我们通常使用逻辑 OR (||) 运算符在 Javascript 中设置默认值。 它具有相同的功能,如果左边的第一个值不满足某些条件,它会设置一个值。 然而,|| 如果左边的值是 falsy ,则运算符返回右边的值 - 并且有很多 falsy 值,如下面的列表所示。

Falsy 值 :

  • false
  • 0 或者 -0 或者 0n
  • 任何空字符串,例如: ""
  • null
  • undefined
  • NaN

因此,使用 || 运算符意味着如果一个函数返回值 0,而我们确实想使用 0 值,我们将无法使用 - 因为 0 为假。 使用 nullish 合并运算符 (??),0 是一个有效值,因为它仅在值为 nullundefined 时触发:

// 设置为 0
let x = 0 ?? 5;

// 设置为 5
let y = 0 || 5;

同样,如果字符串为空,|| 运算符将默认为右侧 - 这并不总是所需的行为。 这 ?? 运算符让我们避免这种情况:

// 设置为 ""
let x = "" ?? "default text";

// 设置为 "default text"
let x = "" || "default text";

链接 nullish coalescing 运算符

也可以链接 nullish coalescing 运算符,如下所示:

// 设置为 "default text"
let x = null ?? undefined ?? "default text";

但是你不能用逻辑 || 运算符链接它,除非带括号:

// 错误输出:
let x = 0 || undefined ?? "default text";

// 返回 "default text";
let y = (0 || undefined) ?? "default text";

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便