如何在JavaScript中检查null值
null值 表示任何对象值的不出现。通常有意设置它以指示变量已声明但尚未分配任何值。
这与类似的原始值 相比,有不同的地方 undefined
,后者是任何对象值的无意缺席。
这是因为已声明但未分配任何值的变量是 undefined
,而不是 null 。
方法:
JavaScript中有很多检查值是否为null的方法:
- 使用等号运算符(
===
) - 通过Object.is()函数
- 通过typeof运算符
1. 使用等号运算符(===
): 使用该运算符,我们将学习如何通过(===
)运算符检查JavaScript中的null值。此运算符仅适用于 null 值,而不适用于 undefined , false,0,NaN 。
语法:
x === y;
2. 通过Object.is()函数: 此函数检查两个对象的值是否相等。如果它们相同,则两个对象的值都为null。
语法:
Object.is(a,null);
3. 通过typeof运算符: 使用typeof运算符非常有用,因为如果变量未声明,则将显示ReferenceError。但是,非声明值的typeof是undefined,因此使用typeof是检查null和undefined变量的更好方法。
语法:
typeof var;
示例:
<script>
// 这将安全地检查一个值,以确保它已经被声明并分配了一个值
// 而不是null或undefined:
console.log(typeof undeclaredVariable !== "undefined"
&& (typeof undeclaredVariable !== "object"
|| !undeclaredVariable))
// 与使用==检查null相比,
// 这只适用于已声明的变量:
try { undeclaredVariable == null }
catch (e) { console.log(e) }
try { undeclaredVariable === null }
catch (e) { console.log(e) }
try { undeclaredVariable === undefined }
catch (e) { console.log(e) }
let declaredButUndefinedVariable
// 已经被声明但未赋值的值将具有undefined的值,其类型为undefined
console.log(typeof declaredButUndefinedVariable
!== "undefined" &&
(typeof declaredButUndefinedVariable !== "object"
|| !declaredButUndefinedVariable))
let stringVariable = "Here's Johnny!"
// 如果变量已被声明并分配了一个既不是null也不是undefined的值,
// 我们将得到true。
console.log(typeof stringVariable !== "undefined" &&
(typeof stringVariable !== "object" || !stringVariable))
// 这可以用于创建一个函数,该函数对于undefined、未声明和null值
// 都将返回false。
const isNotNullNorUndefined =
(value) => typeof value !== "undefined"
&& (typeof value !== "object" || !value)
console.log(isNotNullNorUndefined(stringVariable))
</script>
结果
...js:7:7)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:22:47
ReferenceError: undeclaredVariable is not defined
at Object.<anonymous> (/home/guest/sandbox/55da4d93-5c09-4cd3-8be9-a1459e8ed1b0.js:8:7)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:22:47
false
true
true
阅读更多:JavaScript 教程