首页 文章

如何在JavaScript中检查未定义的变量

提问于
浏览
795

我想检查变量是否已定义 . 例如,以下引发了未定义的错误

alert( x );

我怎么能抓到这个错误?

13 回答

  • 1533

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

    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);
    
  • 0

    另一个潜在的"solution"是使用 window 对象 . 它避免了在浏览器中的引用错误问题 .

    if (window.x) {
        alert('x exists and is truthy');
    } else {
        alert('x does not exist, or exists and is falsy');
    }
    
  • 0

    在JavaScript中, null 是一个对象 . 那里有's another value for things that don', undefined . 对于几乎所有无法在文档中找到某些结构的情况,DOM都会返回 null ,但在JavaScript本身中 undefined 是使用的值 .

    第二,不,没有直接的等价物 . 如果你真的想特意检查 null ,请执行:

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

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

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

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

    如果您知道该变量存在,并想检查其中是否存储了任何值:

    if (yourvar !== undefined)
    

    如果您想知道成员是否存在独立但不关心其 Value 是什么:

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

    如果你想知道变量是否是truthy

    if (yourvar)
    

    Source

  • 1

    接受的答案是正确的 . 只想添加一个选项 . 您也可以使用 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 块,这有点乱,因为它创建了块级范围 . 当然,这个例子非常简化,可以回答问题,但不包括错误处理方面的最佳实践;) .

  • 2

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

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

    EDIT:

    在不初始化变量的情况下,将抛出异常“未捕获的ReferenceError:变量未定义...”

  • 0

    我们可以按如下方式检查 undefined

    var x; 
    
    if (x === undefined) {
        alert("x is undefined");
    } else {
         alert("x is defined");
    }
    
  • 0

    该错误告诉您 x 甚至不存在!它不是 declared ,这与 assigned 不同 .

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

    如果您声明 x ,则不会出现错误 . 您将收到一条警告,其中显示 undefined 因为已声明 x 已存在/但尚未分配值 .

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

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

    这是检查 x 中存储的值的类型 . 它只会在 x 尚未声明时返回 undefined ,如果它已被声明且尚未分配 .

  • 0

    更简单,更简便的版本是:

    if (!x) {
       //Undefined
    }
    

    要么

    if (typeof x !== "undefined") {
        //Do something since x is defined.
    }
    
  • 1

    对于传递给它的任何参数/表达式,void运算符返回 undefined . 所以你可以测试结果(实际上一些minifiers将你的代码从 undefined 更改为 void 0 以保存几个字符)

    例如:

    void 0
    // undefined
    
    if (variable === void 0) {
        // variable is undefined
    }
    
  • 309

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

    typeof x === "undefined"
    

    你有时会变得懒惰和使用

    x == null
    

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

  • 61

    我使用一个小函数来验证已声明的变量,这确实减少了我的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 }
    
  • 15

    我经常这样做:

    function doSomething(variable)
    {
        var undef;
    
        if(variable === undef)
        {
             alert('Hey moron, define this bad boy.');
        }
    }
    
  • 13

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

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

    此线程中的其他一些解决方案将使您相信变量未定义,即使它已被定义(例如,值为NULL或0) .

相关问题