迹忆客 专注技术分享

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

使用 JavaScript 将 NULL 转换为 0

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

使用三元运算符将 NULL 转换为 0,例如 const result = val === null ? 0 : val。 如果该值等于 null,则运算符返回 0,否则返回该值。

let val = null;

val = val === null ? 0 : val;

console.log(val); // 👉️ 0

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

如果问号左边的表达式计算为真值,则返回冒号左边的值,否则返回右边的值。

真值是所有不为假的值。

JavaScript 中的假值是 nullundefinedfalse0""(空字符串)、NaN(不是数字)。

如果 val 变量存储空值,问号前的表达式返回 true,三元运算符返回 0。

如果表达式返回 false,则运算符返回存储在 val 变量中的值。

另一种方法是使用简单的 if 语句。

let val = null;

if (val === null) {
  val = 0;
}

console.log(val); // 👉️ 0

使用 let 关键字声明 val 变量允许我们在存储的值等于 null 时重新分配它。

虽然这种方法有点冗长,但它仍然很容易阅读。

或者,您可以使用逻辑或 (||) 运算符。

let val = null;

val = val || 0;

console.log(val); // 👉️ 0

如果左边的值是假的,则逻辑或 (||) 运算符返回右边的值。

这意味着我们没有显式检查值是否等于 null,而是检查该值是否为假。 所以它可能是一个空字符串、undefined、NaN 等。

一个简单的考虑方法是,运算符右侧的值是一个备用值,以防左侧的值是假的。

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便