使用 JavaScript 将 NULL 转换为 0
使用三元运算符将 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 中的假值是 null
、undefined
、false
、0
、""
(空字符串)、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 等。
一个简单的考虑方法是,运算符右侧的值是一个备用值,以防左侧的值是假的。
相关文章
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 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。