gpt4 book ai didi

javascript - 我应该什么时候使用?? (无效合并)vs || (逻辑或)?

转载 作者:行者123 更新时间:2023-12-01 15:53:54 24 4
gpt4 key购买 nike

相关 Is there a "null coalescing" operator in JavaScript? - JavaScript 现在有一个 ??我看到的运算符使用频率更高。以前大多数 JavaScript 代码使用 || .

let userAge = null

// These values will be the same.
let age1 = userAge || 21
let age2 = userAge ?? 21

什么情况下会??||表现不同?

最佳答案

OR 运算符 ||如果 left 为 falsy,则使用正确的值, 而空值合并运算符 ??如果 left 为 null,则使用正确的值或 undefined .
如果缺少第一个运算符,这些运算符通常用于提供默认值。
但是 OR 运算符 ||如果您的左值可能包含 "",则可能会出现问题或 0false (因为这些是 falsy values ) :

console.log(12 || "not found") // 12
console.log(0 || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log("" || "not found") // "not found"

console.log(true || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null || "not found") // "not found"
在许多情况下,如果 left 是 null,您可能只需要正确的值。或 undefined .这就是无效的合并运算符 ??是为了:
console.log(12 ?? "not found") // 12
console.log(0 ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log("" ?? "not found") // ""

console.log(true ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null ?? "not found") // "not found"
??运算符在 current LTS versions of Node 中不可用(v10 和 v12),您可以将它与某些版本的 TypeScript 或 Node 一起使用: ??运算符已添加到 TypeScript 3.7回到 2019 年 11 月。
最近, ??运算符是 included in ES2020 ,由 Node 14(2020 年 4 月发布)支持。
当空值合并运算符 ??受支持,我通常使用它而不是 OR 运算符 || (除非有充分的理由不这样做)。

关于javascript - 我应该什么时候使用?? (无效合并)vs || (逻辑或)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com