JavaScript 如何检查“undefined”值
在JavaScript中, ‘undefined’ 是一个原始值,表示已声明但尚未分配值的变量,没有返回语句的函数或不存在的对象属性。
有几种方法可以检查 ‘undefined’ 。
- 使用 ‘typeof’ 运算符
- 与 ‘undefined’ 值进行比较
方法1: 使用 ‘typeof’ 运算符:
语法:
Javascript
// Declare a variable
let myVariable;
// Condition to check variable is defined or not
if (typeof myVariable === "undefined") {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
在这里,如果变量没有被赋值,’typeof’操作符会返回字符串’undefined’。
输出:
myVariable is undefined
方法2: 与 ‘undefined’ 值进行比较:
语法:
Javascript
// Declare a variable
let myVariable;
// Condition to check variable is defined or not
if (myVariable === undefined) {
console.log("myVariable is undefined");
} else {
console.log("myVariable is defined");
}
在这里,===
运算符检查变量的值是否完全等于’undefined’。
输出:
myVariable is undefined
例子1:
JavaScript
// Using the 'typeof' operator:
// Declare a variable
let fruit;
// Condition for check variable is defined or not
if (typeof fruit === "undefined") {
console.log("fruit is undefined");
} else {
console.log("fruit is defined");
}
输出:
fruit is undefined
例子2:
JavaScript
// Using the 'typeof' operator:
// Declare a variable and assign a value
// it will return fruit is defined
let fruit = "apple";
// Condition for check variable is defined or not
if (typeof fruit === "undefined") {
console.log("fruit is undefined");
} else {
console.log("fruit is defined");
}
输出:
fruit is defined
示例3:
JavaScript
// Comparing with the 'undefined' value:
// Declare a variable
let profile;
// Condition for check variable is defined or not
if (profile === undefined) {
console.log("profile is undefined");
} else {
console.log("profile is defined");
}
输出:
profile is undefined
示例 4:
JavaScript
// Comparing with the 'undefined' value:
// Declare a variable and assign value
let profile = "geeksforgeeks";
// Condition for check variable is defined or not
if (profile === undefined) {
console.log("profile is undefined");
} else {
console.log("profile is defined as", profile);
}
输出:
profile is defined as geeksforgeeks