JavaScript 中是否有標準函式用來檢查空值、未定義值或者變數為空值。
不,JavaScript 中沒有用於檢查空值、未定義值或變數為空值的標準函式。但是,JavaScript 中存在真值和假值的概念。
在條件語句中強制轉換為真的值稱為真值。解析為假的值稱為假值。
根據 ES 規範,以下值在條件上下文中將求值為假 −
- null
- undefined
- NaN
- 空字串 ("")
- 0
- false
這意味著以下 if 語句都不會執行 −
if (null) if (undefined) if (NaN) if ("") if (0) if (false)
用於驗證假值的關鍵字
但是,有一些現有關鍵字可以檢查變數是否為 null、未定義或為空。它們是null和undefined。
示例
以下示例驗證 null、未定義和空值 −
<!DOCTYPE html> <html> <head> <title>To check for null, undefined, or blank variables in JavaScript</title> </head> <body style="text-align: center;"> <p id="output"></p> <script> function checkType(x) { if (x == null) { document.getElementById('output').innerHTML += x+'The variable is null or undefined' + '<br/>'; } else if (x == undefined) { document.getElementById('output').innerHTML += 'The variable is null or undefined' + '<br/>'; } else if (x == "") { document.getElementById('output').innerHTML += 'The variable is blank' + '<br/>'; } else { document.getElementById('output').innerHTML += 'The variable is other than null, undefined and blank' + '<br/>'; } } var x; checkType(null); checkType(undefined); checkType(x); checkType(""); checkType("Hi"); </script> </body> </html>
廣告