Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
條件 (三元) 運算子 是 JavaScript 唯一用到三個運算元的運算子:在一個條件後面會跟著一個問號 (?),如果條件是 truthy,在冒號(:)前的表達式會被執行,如果條件是 falsy,在冒號後面的表達式會被執行,這個運算子常常被用來當作 if 的簡潔寫法.
值用來做為條件的表達式
exprIfTrue如果 condition 的值是 truthy (等於或是可轉換為 true) , exprIfTrue 會被執行
exprIfFalse如果 condition 的值是 falsy (等於或是可轉換為 false) , exprIfFalse 會被執行
除了 false, 可能是 falsy 的表達式有 null, NaN, 0, 空字串 ("") 和 undefined. 如果condition 是他們其中之一 , 那麼條件表達式的結果會是 exprIfFalse 的執行結果.
一個簡單的範例:
一個常用來處理 null 的用法 :
條件 (三元) 運算子是右相依性的 (right-associative), 代表他可以以下面的方式鏈結 , 類似於 if … else if … else if … else 的鏈結方法 :
| ECMAScript® 2027 Language Specification # sec-conditional-operator |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月16日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.