迹忆客 专注技术分享

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

使用 JavaScript 设置变量的值为 Null

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

如果变量等于 null,则使用逻辑空值赋值运算符来设置变量的值,例如 myVar ??= 'new value'。 逻辑空值赋值 ??= 运算符将提供的值分配给等于 nullundefined 的变量。

let v1 = null;

v1 ??= 'new value';
console.log(v1); // 👉️ "new value"

如果 v1 变量存储空值或未定义值,我们使用逻辑空值赋值 ??= 运算符为它赋值。

如果 v1 变量的值不等于 null 或 undefined,则逻辑空值赋值运算符短路并且不会将值赋给变量。

请注意 ,我们使用 let 关键字来声明变量,如果我们使用 const,我们将无法重新分配它。

另一种方法是使用无效合并 ?? 运算符。

如果变量为 Null,则使用 Nullish Coalescing 设置变量的值

要设置变量的值是否等于 null,请使用 nullish 合并运算符,例如 myVar = myVar ?? 'new value'。 如果左侧计算结果为 null 或未定义,则空值合并运算符返回右侧操作数,否则返回左侧操作数。

let v1 = null;

v1 = v1 ?? 'new value';
console.log(v1); // 👉️ "new value"

如果空合并运算符 ?? 左侧的值等于 nullundefined,则返回右侧的值,否则返回运算符左侧的值。

如果存储在 v1 变量中的值不是 nullundefined,它将被赋予字符串新值,否则它将被赋予当前值。

如果变量为 Null,则使用三元设置变量的值

如果变量等于 null,则使用三元运算符设置变量的值,例如 v1 = v1 === null ? 'new value' : v1;。 如果左侧条件的计算结果为真值,则三元运算符返回冒号左侧的值,否则返回右侧的值。

let v1 = null;

v1 = v1 === null ? 'new value' : v1;
console.log(v1); // 👉️ "new value"

三元运算符与 if/else 语句非常相似。

如果条件 v1 === null 返回真,则返回冒号左边的值,否则返回右边的值。

我们的条件检查 v1 变量中的值是否等于 null,如果是,我们将变量分配给新值的字符串,否则我们将其重新分配给它的当前值。

转载请发邮件至 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

在 Pandas 中加载 JSON 文件

发布时间:2024/04/21 浏览次数:105 分类:Python

本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。

将 JSON 转换为 Pandas DataFrame

发布时间:2024/04/20 浏览次数:135 分类:Python

本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。

扫一扫阅读全部技术教程

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便