995

我想检查变量是否已定义。例如,以下抛出未定义的错误

alert( x );

我怎样才能捕捉到这个错误?

4

15 回答 15

1796

在 JavaScript 中,null是一个对象。不存在的事物还有另一个价值,undefined. DOMnull在几乎所有无法在文档中找到某些结构的情况下都会返回,但在 JavaScript 本身undefined中就是使用的值。

其次,不,没有直接的等价物。如果您真的想专门检查null,请执行以下操作:

if (yourvar === null) // Does not execute if yourvar is `undefined`

如果要检查变量是否存在,只能使用try/来完成catch,因为typeof会将未声明的变量和使用值声明的变量undefined视为等效的。

但是,要检查变量是否已声明且未undefined声明:

if (yourvar !== undefined) // Any scope

以前,必须使用typeof运算符安全地检查 undefined,因为可以undefined像变量一样重新分配。旧方式如下所示:

if (typeof yourvar !== 'undefined') // Any scope

undefined可重新分配的问题已在 2009 年发布的 ECMAScript 5 中得到修复。您现在可以安全地使用===!==测试,undefined而无需使用一段typeof时间undefined以来一直是只读的。

如果你想知道一个成员是否独立存在但不关心它的值是什么:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

如果您想知道变量是否为

if (yourvar)

来源

于 2009-05-13T14:11:30.320 回答
381

真正测试变量是否undefined是的唯一方法是执行以下操作。请记住,未定义是 JavaScript 中的一个对象。

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

这个线程中的一些其他解决方案会让你相信一个变量是未定义的,即使它已经定义(例如,值为 NULL 或 0)。

于 2009-05-13T14:53:55.867 回答
72

从技术上讲,正确的解决方案是(我相信):

typeof x === "undefined"

你有时会变得懒惰并使用

x == null

但这允许未定义的变量 x 和包含 null 的变量 x 返回 true。

于 2009-05-13T14:12:29.943 回答
20

一个更简单、更简写的版本是:

if (!x) {
   //Undefined
}

或者

if (typeof x !== "undefined") {
    //Do something since x is defined.
}
于 2009-05-13T14:26:03.493 回答
16

我经常这样做:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}
于 2009-05-13T14:45:39.000 回答
5

void运算符返回undefined传递给它的任何参数/表达式。因此您可以针对结果进行测试(实际上一些缩小器将您的代码从 更改undefinedvoid 0以保存几个字符)

例如:

void 0
// undefined

if (variable === void 0) {
    // variable is undefined
}
于 2018-07-02T14:07:23.343 回答
4

该错误告诉您x甚至不存在!它还没有被声明,这与被赋值不同。

var x; // declaration
x = 2; // assignment

如果您声明x,您将不会收到错误消息。您会收到一条警报,说明undefined因为x存在/已声明但尚未分配值。

要检查变量是否已声明,您可以使用typeof,任何其他检查变量是否存在的方法都会引发您最初遇到的相同错误。

if(typeof x  !==  "undefined") {
    alert(x);
}

这是检查存储在 中的值的类型x。它只会undefinedx尚未声明或声明但尚未分配时返回。

于 2018-01-10T06:33:42.990 回答
3

另一个潜在的“解决方案”是使用window对象。它避免了在浏览器中的引用错误问题。

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}
于 2017-11-13T20:16:31.537 回答
3

很抱歉死灵,但这里的大多数答案都混淆了“未定义”和“未定义”

  1. 未定义- 声明了一个变量,但它的值未定义。

  2. 未定义- 甚至没有声明变量。

检查这两种情况的唯一安全方法是使用typeof myVar === 'undefined'

myVar === undefined只会检查案例编号 (1)。myVar如果甚至没有声明,它仍然会为案例编号 (2) 抛出“myVar is not defined” 。OP专门询问“甚至没有定义”的情况(2)。

PS 我确实理解“案例 2”在现代 ES6 世界中变得越来越少,但一些旧的遗留组件仍然存在于过去。

于 2021-11-12T09:46:46.740 回答
2

我经常使用最简单的方法:

var variable;
if (variable === undefined){
    console.log('Variable is undefined');
} else {
    console.log('Variable is defined');
}

编辑:

不初始化变量,会抛出异常“Uncaught ReferenceError: variable is not defined...”

于 2015-12-09T08:44:22.770 回答
2

您还可以使用三元条件运算符:

var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);

于 2016-02-12T12:02:28.917 回答
2

接受的答案是正确的。只是想再添加一个选项。您也可以使用try ... catch块来处理这种情况。一个怪异的例子:

var a;
try {
    a = b + 1;  // throws ReferenceError if b is not defined
} 
catch (e) {
    a = 1;      // apply some default behavior in case of error
}
finally {
    a = a || 0; // normalize the result in any case
}

请注意catch块,这有点混乱,因为它创建了块级范围。而且,当然,该示例非常简化以回答所提出的问题,它不包括错误处理的最佳实践;)。

于 2017-08-11T17:25:00.077 回答
2

只需执行以下操作:

function isNotDefined(value) {
  return typeof value === "undefined";
}

并称之为:

isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
于 2019-01-31T12:08:03.267 回答
1

我们可以检查undefined如下

var x; 

if (x === undefined) {
    alert("x is undefined");
} else {
     alert("x is defined");
}
于 2016-07-04T17:17:18.303 回答
1

我使用一个小函数来验证变量是否已被声明,这确实减少了我的 javascript 文件中的杂乱程度。我添加了对该值的检查,以确保该变量不仅存在,而且还被分配了一个值。第二个条件检查变量是否也已实例化,因为如果变量已定义但未实例化(参见下面的示例),如果您尝试在代码中引用它的值,它仍然会抛出错误。

未实例化 -var my_variable;已实例化 -var my_variable = "";

function varExists(el) { 
  if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) { 
    return true; 
  } else { 
    return false; 
  } 
}

然后,您可以使用条件语句来测试变量是否已像这样定义和实例化......

if ( varExists(variable_name) ) { // checks that it DOES exist } 

或者测试它没有被定义和实例化使用......

if( !varExists(variable_name) ) { // checks that it DOESN'T exist }
于 2018-07-05T17:48:51.457 回答