How can I check if a variable exist in JavaScript?

后端 未结 8 2062
再見小時候
再見小時候 2020-12-14 01:41

I am not asking if the variable is undefined or if it is null. I want to check if the variable exists or not. Is this possible?

相关标签:
8条回答
  • 2020-12-14 02:33
    if ('bob' in window) console.log(bob);
    

    Keep in mind with this way, even if you declared a variable with var, that would mean it exists.

    0 讨论(0)
  • 2020-12-14 02:35

    The typeof techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined.

    But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error. So this should work:

    var exists = true;
    try {
        if (someVar)
            exists = true;
    } catch(e) { exists = false; }
    if (exists)
       // do something - exists only == true if someVar has been declared somewhere.
    
    0 讨论(0)
提交回复
热议问题