可以使用 typeof 操作符来判断一个变量是否为 undefined 类型

   let x;

 if (typeof x === "undefined") {
console.log("x is undefined");
 } else {
console.log("x is defined");
 }

  也可以使用严格相等运算符 === 来判断一个变量是否为 undefined

   let x;

 if (x === undefined) {
console.log("x is undefined");
 } else {
console.log("x is defined");
 }

  注意:不要使用 == 运算符来判断一个变量是否为 undefined 因为它会在比较之前进行类型转换js判断对象是否undefinedjs判断对象是否undefined,可能导致意外的结果。

  如果要判断一个变量是否未定义(既未声明也未赋值),可以使用 window.variable 来进行判断,如果变量未定义,则会抛出一个 ReferenceError 错误

   let x;

 try {
if (window.x === undefined) {
  console.log("x is undefined");
}
 } catch (error) {
if (error instanceof ReferenceError) {
  console.log("x is not defined");
}
 }
TAGS:变量 js判断对象是否undefined js判断对象是否为null js判断json对象是否为空
!如链接失效请在下方留言。本站所有资源均来源于网络,版权属于原作者!仅供学习参考,本站不对您的使用负任何责任。如果有侵权之处请第一时间联系我们删除,敬请谅解!