JavaScript中检查空字符串、未定义或空值的方法
技术背景
在JavaScript开发中,经常需要检查一个字符串是否为空、未定义或者为null。不同的场景可能需要不同的检查方式,例如简单的空字符串检查、考虑空白字符的检查等。了解各种检查方法及其适用场景,对于编写健壮的代码至关重要。
实现步骤
检查真值和假值
- 检查真值:使用条件判断语句,若变量为真值(非空字符串、true、42、Infinity、[]等),则执行相应代码。
- 检查假值:使用取反操作符,若变量为假值(空字符串、false、0、null、undefined等),则执行相应代码。
精确检查空字符串
- 严格相等检查:使用
===
操作符,检查变量是否严格等于空字符串。
1 2 3
| if (strValue === "") { }
|
- 严格不相等检查:使用
!==
操作符,检查变量是否严格不等于空字符串。
1 2 3
| if (strValue !== "") { }
|
检查变量是否为假值或长度为零
1 2 3
| function isEmpty(str) { return (!str || str.length === 0 ); }
|
或者使用可选链和箭头函数简化:
1
| const isEmpty = (str) => (!str?.length);
|
检查变量是否为假值或仅包含空白字符
1 2 3
| function isBlank(str) { return (!str || /^\s*$/.test(str)); }
|
猴子补丁方式
可以对String
原型进行扩展,但这种方式存在争议,可能会破坏依赖内置类型现有结构的代码。
1 2 3 4
| String.prototype.isEmpty = function() { return (this.length === 0 || !this.trim()); }; console.log("example".isEmpty());
|
使用双重非操作符或类型转换
1 2 3 4 5 6 7
| if (!!str) { }
if (Boolean(str)) { }
|
自定义函数检查多种情况
1 2 3 4 5 6 7 8 9 10 11 12 13
| function empty(e) { switch (e) { case "": case 0: case "0": case null: case false: case undefined: return true; default: return false; } }
|
使用lodash库
它可以处理多种情况,如{}
, ''
, null
, undefined
等,但对于Number
类型总是返回true
。
通用的“一体化”函数(不推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function is_empty(x) { return ( (typeof x == 'undefined') || (x == null) || (x == false) || (x.length == 0) || (x == 0) || (x == "") || (x.replace(/\s/g,"") == "") || (!/[^\s]/.test(x)) || (/^\s*$/.test(x)) ); }
|
检查字符串是否有效
1
| const validStr = (str) => str ? true : false;
|
检查字符串是否不为空或仅包含空白字符
1 2
| const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0; const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
|
核心代码
以下是一些常用的检查函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function isEmpty(str) { return (!str || str.length === 0 ); }
function isBlank(str) { return (!str || /^\s*$/.test(str)); }
const validStr = (str) => str ? true : false;
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0; const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
|
最佳实践
- 简单场景:如果只需要简单判断字符串是否为空,使用
if (strValue === "")
或if (!strValue.length)
即可。 - 考虑空白字符:如果需要考虑字符串仅包含空白字符的情况,使用
isBlank
函数。 - 使用库:如果项目中已经使用了lodash库,可以使用
_.isEmpty
函数处理多种情况。
常见问题
- 猴子补丁的风险:对内置类型进行猴子补丁可能会破坏依赖内置类型现有结构的代码,不建议在公共库或多人协作的项目中使用。
- 性能问题:使用正则表达式(如
test
、replace
)和charAt
的方法在所有浏览器中性能较慢,而基于!str
、==
、===
和length
的简单方法性能较快。 - 类型判断:在使用检查函数时,要明确目标变量的类型,避免不必要的判断。例如,如果确定变量是字符串,就不需要检查是否为
null
或undefined
。