Checking if a variable exists in javascript

后端 未结 7 1141
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:57

    I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

    If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

    is not the only way. One can do just:

    this.hasOwnProperty("bar")
    

    to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

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