是否有标准函数来检查 JavaScript 中变量是否为空、未定义或空白?
javascriptobject oriented programmingprogramming
没有标准函数来检查 JavaScript 中变量是否为空、未定义或空白。但是,JavaScript 中有 truthy 和 falsy 值的概念。
在条件语句中强制为真的值称为真值。那些解析为 false 的被称为 falsy。
根据 ES 规范,以下值在条件上下文中将被评估为 false −
- null
- undefined
- NaN
- 空字符串 ("")
- 0
- false
这意味着以下 if 语句都不会被执行 −
if (null) if (undefined) if (NaN) if ("") if (0) if (false)
用于验证 falsys 的关键字
但是有一些现有的关键字可以检查变量是否为 null、undefined 或空白。它们是 null 和 undefined。
示例
以下示例验证 null、undefined 和空白值 −
<!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>