如何在JavaScript中检查“undefined”值
在JavaScript中, ‘ undefined’ 是一个原始值,表示一个已经声明但未赋值的变量,没有返回语句的函数,或者不存在的对象属性。
有几种方法可以检查 ‘undefined’ 。
- 使用 ‘typeof’ 运算符
- 与 ‘undefined ‘ 值进行比较
方法1: 使用 ‘typeof’ 运算符:
语法:
// 声明一个变量
let myVariable;
// 检查变量是否已定义
if (typeof myVariable === "undefined") {
console.log("myVariable是未定义的");
} else {
console.log("myVariable被定义了");
}
在这里,如果变量没有被赋值,‘typeof’运算符返回字符串‘undefined’。
输出:
myVariable是未定义的
方法2: 与 ‘undefined’ 值进行比较:
语法:
// 声明一个变量
let myVariable;
// 检查变量是否已定义
if (myVariable === undefined) {
console.log("myVariable是未定义的");
} else {
console.log("myVariable被定义了");
}
在这里,‘=’运算符检查变量的值是否与‘undefined’完全相等。
输出:
myVariable是未定义的
示例1:
// 使用'typeof'运算符:
// 声明一个变量
let fruit;
// 检查变量是否已定义
if (typeof fruit === "undefined") {
console.log("fruit是未定义的");
} else {
console.log("fruit被定义了");
}
输出:
fruit是未定义的
示例2:
// 使用'typeof'运算符:
// 声明一个变量并赋值
// 它将返回fruit被定义了
let fruit = "apple";
// 检查变量是否已定义
if (typeof fruit === "undefined") {
console.log("fruit是未定义的");
} else {
console.log("fruit被定义了");
}
输出:
fruit被定义了
示例3:
// 与'undefined'值进行比较:
// 声明一个变量
let profile;
// 检查变量是否已定义
if (profile === undefined) {
console.log("profile是未定义的");
} else {
console.log("profile被定义了");
}
输出:
profile是未定义的
示例4:
// 与'undefined'值进行比较:
// 声明一个变量并赋值
let profile = "geeksforgeeks";
// 检查变量是否已定义
if (profile === undefined) {
console.log("profile是未定义的");
} else {
console.log("profile被定义为", profile);
}
输出:
profile被定义为geeksforgeeks
阅读更多:JavaScript 教程