如何检查变量是否已声明,尽管未初始化

How to check if variable has been declared, although uninitialized?

本文关键字:声明 初始化 是否 何检查 检查 变量      更新时间:2023-09-26

如何检查JavaScript变量是否已实际声明?

这个解决方案在我的情况下不起作用:

JavaScript检查变量是否存在(已定义/初始化)

的例子:

(function(){
    var abc;
    alert(typeof abc === 'undefined') // true
})();
一样

:

(function(){
    alert(typeof abc === 'undefined') // true
})();

在两种情况下都产生true。我可以这样做:

(function(){
    var abc;
    var isDefined = false;
    try { isDefined = abc || !abc; }
    catch(e) {}
    alert(isDefined); // true
})();

它工作,但我正在寻找更好的东西,x浏览器。

EDIT:我想在一段动态代码中使用它,该代码通过eval运行,并检查某个变量是否存在于局部或全局范围

这个问题已经被问过很多次了,答案是"你不能"(除了使用OP中的try..catch)。

你可以在或hasOwnProperty中使用检查对象的属性,但是这两种方法都要求你可以访问你想要测试的对象。变量属于执行上下文的变量对象(ES 3)或环境记录(ES 5),并且它们是不可访问的,因此您无法检查它们的属性。

特殊情况是全局对象,因为全局变量(即全局环境记录的属性)是全局对象的属性,所以你可以这样做:

var global = this;
var foo;
// Declared but not initialised
foo in global // true
global.hasOwnProperty('foo'); // true
// Not declared or initialised
bar in global  // error
global.hasOwnProperty('bar'); // true
但是,对于IE <版本的全局对象不支持>hasOwnProperty方法。9.

你可以像这样使用"use strict"来检测:

"use strict";
try {
    myVar = 7;
    console.log("myVar is "+myVar);
} catch(e) {
    console.log("error");
}

运行脚本,它将打印"error"。然后注释掉"use strict"并再次运行;它将打印"myVar is 7"