JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1163
孤城傲影
孤城傲影 2020-11-22 00:59

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))



        
29条回答
  •  梦如初夏
    2020-11-22 01:24

    My preference is typeof(elem) != 'undefined' && elem != null.

    However you choose, consider putting the check in a function like so

    function existy (x) {
        return typeof (x) != 'undefined' && x != null;
    }
    

    If you don't know the variable is declared then continue with typeof (x) != 'undefined' && x != null;

    Where you know the variable is declared but may not be existy, you could use

    existy(elem) && doSomething(elem);
    

    The variable you are checking may be a nested property sometimes. You can use prop || {} to go down the line checking existance to the property in question:

    var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
    

    After each property use (...' || {}').nextProp so that a missing property won't throw an error.

    Or you could use existy like existy(o) && existy(o.p) && existy(o.p.q) && doSomething(o.p.q)

提交回复
热议问题