JavaScript中检查空值、未定义值或空白变量的标准函数

JavaScript中检查空值、未定义值或空白变量的标准函数

技术背景

在JavaScript编程中,经常需要检查变量是否为nullundefined或空白,以确保程序的健壮性。JavaScript中的值可以分为nullishnullundefined)、falsy(如nullundefinedNaN、空字符串、0false等)和truthy(非falsy的值)。

实现步骤

检查值是否为nullish

可以使用以下几种方式:

1
2
3
4
if (value == null) { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined) { /* value is nullish */ }
if ((value ?? null) === null) { /* value is nullish */ }

检查值是否不为nullish

1
2
3
4
if (value != null) { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined) { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null) { /* value is not nullish, although it could be falsy */ }

检查值是否为falsy

使用!运算符:

1
if (!value) { /* value is falsy */ }

检查值是否为truthy

1
if (value) { /* value is truthy */ }

数据验证

在实际应用中,仅使用nullishfalsytruthy检查可能无法满足数据验证需求,需要根据具体情况添加额外逻辑。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 检查值是否大于等于0
[null, -1, 0, 1].forEach(num => {
if (num != null && num >= 0) {
console.log("%o is not nullish and greater than/equal to 0", num);
} else {
console.log("%o is bad", num);
}
});

// 检查值是否不是空字符串或仅包含空格的字符串
["", " ", "hello"].forEach(str => {
if (str && /\S/.test(str)) {
console.log("%o is truthy and has non-whitespace characters", str);
} else {
console.log("%o is bad", str);
}
});

// 检查值是否不是空数组
[[], [1]].forEach(arr => {
if (arr && arr.length) {
console.log("%o is truthy and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});

// 使用可选链操作符检查值是否不是空数组
[[], [1]].forEach(arr => {
if (arr?.length) {
console.log("%o is not nullish and has one or more items", arr);
} else {
console.log("%o is bad", arr);
}
});

核心代码

以下是一些自定义的检查函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 检查值是否为空(包括null、undefined、空字符串、空数组、空对象)
function isEmpty(value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
);
}

// 检查值是否为未定义或null
function isEmptySimple(value) {
return (typeof value === "undefined" || value === null);
}

// 检查字符串是否为空或仅包含空格
function stringIsEmpty(value) {
return value ? value.trim().length == 0 : true;
}

最佳实践

  • 使用typeof检查变量是否已声明:在不确定变量是否存在时,使用typeof运算符,如if (typeof foo !== 'undefined')
  • 明确比较nullundefined:使用===进行严格比较,使代码更具可读性。
  • 使用nullish合并运算符??:在处理nullundefined时,使用??来提供默认值。

常见问题

  • 变量未声明:如果直接使用未声明的变量进行检查,会抛出错误。可以使用typeof来避免这种情况。
  • =====的区别==在比较nullundefined时会有特殊处理,而===是严格比较,建议使用===以提高代码的清晰度。

JavaScript中检查空值、未定义值或空白变量的标准函数
https://119291.xyz/posts/2025-05-12.javascript-check-null-undefined-blank-variables/
作者
ww
发布于
2025年5月12日
许可协议