How to check for an undefined or null variable in JavaScript?

前端 未结 24 2296
悲&欢浪女
悲&欢浪女 2020-11-22 15:55

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
             


        
24条回答
  •  我在风中等你
    2020-11-22 16:29

    As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)

    !!window['bleh'];
    

    This would return a false while bleh has not been declared AND assigned a value.

提交回复
热议问题