How can I check if a variable exist in JavaScript?

后端 未结 8 2114
再見小時候
再見小時候 2020-12-14 01:41

I am not asking if the variable is undefined or if it is null. I want to check if the variable exists or not. Is this possible?

8条回答
  •  孤街浪徒
    2020-12-14 02:25

    try this

    var ex=false;
    try {(ex=myvar)||(ex=true)}catch(e) {}
    alert(ex);
    

    where ex is true if myvar has been declared.

    working example: http://jsfiddle.net/wcqLz/

提交回复
热议问题