如何检查变量是未定义的(已声明但未赋值)还是未声明的(不存在)

How do i check if variable is undefined (declared but not assigned a value) vs undeclared (doesn't exist)?

本文关键字:赋值 未声明 声明 不存在 未定义 何检查 检查 变量      更新时间:2023-09-26

两者都会导致"undefined"。。。例如

var a;
typeof blablabl; //"undefined";
typeof a; //"undefined";

检查变量是否未定义或变量是否尚未声明的默认方法是什么;

var a = a || 3;

仅当作用域中已存在变量时才有效。

刚刚测试了我的建议,似乎有效:

"use strict";
try {
  b = 3;
} catch(e) {
  console.log("Caught it:", e);
  // Caught it: ReferenceError: assignment to undeclared variable b
}

如果可以硬编码变量名,则可以测试某些变量(例如b)的初始化,而无需按照以下方式修改其值,

(function () {
    "use strict";
    var foo;
    try {
        foo = b;
        console.log('b', ' is initialised');
    } catch(e) {
        if (e instanceof ReferenceError)
            console.log('b', ' is not initialised');
    }
}());

还要注意,以下没有抛出错误

(function () {
    "use strict";
    var foo;
    var foo;
}());

因此,如果您"不确定",请再次var

如果尚未定义a,则

(a==未定义)将返回true。

如果a尚未定义或a等于null,则(a==undefined)将返回true。

如果你想检查变量是否存在,你可以检查这个范围(如果适用):

var exists=(this.hasOwnProperty('a'))?'a存在于当前作用域":"a不存在";