Checking if a variable exists in javascript

后端 未结 7 1145
Happy的楠姐
Happy的楠姐 2021-01-31 06:58

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:

1) if ( typeof variableName !== \'undefined\' && v

7条回答
  •  被撕碎了的回忆
    2021-01-31 07:51

    if ( typeof variableName !== 'undefined' && variableName )
    //// could throw an error if var doesnt exist at all
    
    if ( window.variableName )
    //// could be true if var == 0
    
    ////further on it depends on what is stored into that var
    // if you expect an object to be stored in that var maybe
    if ( !!window.variableName )
    //could be the right way
    
    best way => see what works for your case
    

提交回复
热议问题