JavaScript 如果要判断变量是否已定义,可以使用 typeof:
- if(typeof someVar == 'undefined') {
- document.write("变量 someVar 未定义");
- } else {
- document.write("变量 someVar 已定义");
- }
JavaScript 如果只想判断已定义变量是否为 true 可以直接使用以下方法:
- if (strValue) {
- // strValue 为 true 执行的代码
- } else {
- // strValue 为 false 执行的代码
- }
以下使用正则的方法判断变量是否已定义并且不为空,比较完整的方法:
- if ( // 返回判断的值
- (typeof x == 'undefined')
- ||
- (x == null)
- ||
- (x == false) //类似: !x
- ||
- (x.length == 0)
- ||
- (x == 0) // 这里是判断 0,不需要刻意去掉
- ||
- (x == "")
- ||
- (x.replace(/\s/g,"") == "")
- ||
- (!/[^\s]/.test(x))
- ||
- (/^\s*$/.test(x))
- ) {
- document.write("变量未定义或为空");
- }
也可以封装一个方法来判断,包含了空值、0、false 等,适用已定义的变量:
- function empty(e) {
- switch (e) {
- case "":
- case 0:
- case "0":
- case null:
- case false:
- case undefined:
- return true;
- default:
- return false;
- }
- }
-
- empty(null) // true
- empty(0) // true
- empty(7) // false
- empty("") // true
- empty((function() {
- return ""
- })) // false