How can I check if a variable exist in JavaScript?

后端 未结 8 2061
再見小時候
再見小時候 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:16

    I use this function:

    function exists(varname){
        try {
            var x = eval(varname);
            return true;
        } catch(e) { return false; }
    }
    

    Hope this helps.

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

    When you try to access a variable which is not declared in the context, you will see that the error message says it is undefined. This is the real check you may perform to see if the variable if defined or not than null check.

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

    If you don't need to know at runtime use JSLint. Also remember that javascript var statements are hoisted, so even if the var is inside an if block it will still be defined.

    Honestly I think if you are not sure if a variable is defined you are doing something wrong and should refactor your code.

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

    I think it depends on what you want to do with the variable.

    Let's say, for example, you have a JS library that will call a function if it has been defined and if not, then not. You probably know already that functions are first level objects in JS and are as such variables.

    You could be tempted to ask first if it exists, and then call it. But you can just as well wrap the attempt at calling it in a try/catch block.

    Example of code that calls a function, if defined, before and after firing an event:

    function fireEvent(event)
    {
        try
        {
            willFireEvent(event); // Is maybe NOT defined!
        } catch(e) {}
    
        //... perform handler lookup and event handling
    
        try
        {
            hasFiredEvent(event); // Might also NOT exist!
        } catch(e) {}
    }
    

    So instead of checking for the variable, catch the error instead:

    var x;
    
    try
    {
        x = mayBeUndefinedVar;
    }
    catch (e)
    {
        x = 0;
    }
    

    Whether this is a good thing or not in terms of performance, etc., depends on what you're doing...

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

    What you're after is:

    window.hasOwnProperty("varname");
    

    A safer approach might even be:

    this.hasOwnProperty("varname");
    

    Depends on your calling context though...

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

    try this

    var ex=false;
    try {(ex=myvar)||(ex=true)}catch(e) {}
    alert(ex);
    

    where ex is true if myvar has been declared.

    working example: http://jsfiddle.net/wcqLz/

    0 讨论(0)
提交回复
热议问题