JavaScript check if variable exists (is defined/initialized)

前端 未结 29 1632
孤城傲影
孤城傲影 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:35

    Attention :: people who don't understand the difference between a proposition let, a constant const and a variable var should refrain themselves from commenting.

    These answers (aside from the Fred Gandt solution ) are all either incorrect or incomplete.

    Suppose I need my variableName; to carry an undefined value, and therefore it has been declared in a manner such as var variableName; which means it's already initialized; - How do I check if it's already declared?

    Or even better - how do I immediately check if "Book1.chapter22.paragraph37" exists with a single call, but not rise a reference error?

    We do it by using the most powerful JasvaScript operator, the in operator.:

    "[variable||property]" in [context||root] 
    >> true||false
    

    In times of AJAX peaking popularity I've written a method (later named) isNS() which is capable of determining if the namespace exists including deep tests for property names such as "Book1.chapter22.paragraph37" and a lot more.

    But since it has been previously published and because of its great importance it deserves to be published in a separate thread I will not post it here but will provide keywords (javascript + isNS ) which will help you locate the source code, backed with all the necessary explanations.

提交回复
热议问题