JavaScript 中关于 ?? 和 || 的区别和相似性

当处理默认值时,??(空值合并运算符)和||(逻辑或运算符)是 JavaScript 中的两个重要工具。尽管它们的目标相似,但它们在实现和使用上存在一些关键区别。本文将详细探讨它们的区别和相似之处。

一、相似性

用途:

 ?? 和 || 都用于在值可能是假值或缺失时提供默认值。

返回值:

两者都返回一个值,而不是布尔值。这使它们不同于通常的逻辑或布尔运算。

二、区别

优先级:

?? 的优先级比 || 高。这意味着在表达式中同时使用它们时,?? 将首先计算。这可能会导致不同的行为,特别是当你想要设置默认值时。

处理假值:

?? 只处理严格等于 null 或 undefined 的情况。它不会处理其他假值,如 0、false、空字符串 ” 等。只有在左侧操作数是 null 或 undefined 时,?? 才会返回右侧操作数。

|| 处理更广泛的假值情况,包括 null、undefined、false、0、NaN、空字符串 ” 等。如果左侧操作数是假值,|| 会返回右侧操作数。

const a = null;
const b = 0;

const result1 = a ?? 'Default';  // result1为 'Default',因为a是null
const result2 = b ?? 'Default';  // result2为 0,因为b不是null

const result3 = a || 'Default';  // result3为 'Default',因为a是null
const result4 = b || 'Default';  // result4为 'Default',因为b是假值

console.log(1 || "xx") 			//1
console.log(0 || "xx") 			//xx
console.log(null || "xx")		//xx
console.log(undefined || "xx")  //xx
console.log(-1 || "xx") 		//-1
console.log("" || "xx") 		//xx

console.log(1 ?? "xx")			//1
console.log(0 ?? "xx") 			//0
console.log(null ?? "xx") 		//xx
console.log(undefined ?? "xx")  //xx
console.log(-1 ?? "xx") 		//-1
console.log("" ?? "xx") 		//''
欢迎阅读!

评论

  1. Harlan1010
    Windows Chrome
    3 周前
    2025-8-05 13:43:53
  2. Ivan4637
    Windows Chrome
    3 周前
    2025-8-05 23:15:14
  3. Stanley29
    Windows Chrome
    3 周前
    2025-8-07 16:06:09
  4. Josiah3350
    Windows Chrome
    3 周前
    2025-8-08 5:23:47
  5. Kaleb4963
    Windows Chrome
    2 周前
    2025-8-08 15:39:22
  6. Hallie1391
    Windows Chrome
    2 周前
    2025-8-08 21:40:48
  7. Kirsten784
    Windows Chrome
    2 周前
    2025-8-09 18:27:27
  8. Maddison1466
    Windows Chrome
    2 周前
    2025-8-12 6:41:49
  9. Jace3360
    Windows Chrome
    2 周前
    2025-8-12 14:02:46
  10. Cole4116
    Windows Chrome
    2 周前
    2025-8-13 0:37:07
  11. Barret1363
    Windows Chrome
    2 周前
    2025-8-13 2:57:41
  12. Cadence408
    Windows Chrome
    2 周前
    2025-8-13 18:30:20
  13. Samuel2178
    Windows Chrome
    2 周前
    2025-8-14 4:06:47
  14. Chris4169
    Windows Chrome
    2 周前
    2025-8-14 12:30:41
  15. Dora733
    Windows Chrome
    1 周前
    2025-8-18 17:29:25
  16. Frederick4326
    Windows Chrome
    6 天前
    2025-8-19 23:20:23
  17. Giselle488
    Windows Chrome
    3 天前
    2025-8-22 10:50:44
  18. Nova3946
    Windows Chrome
    12 小时前
    2025-8-25 7:27:56
  19. Ron4727
    Windows Chrome
    4 小时前
    2025-8-25 15:49:57

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇