Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - How to check if a variable or object is undefined?

I always thought I could just check an undefined var by comparing it to undefined, but this is the error I get in the chrome console :

enter image description here

How how do i check for the object jQuery being undefined ?

EDIT :

enter image description here

if(jQuery) is giving me problems too

EDIT :

solution :

if(window.jQuery) works. typeof(jQuery) == 'undefined' works too.

Could anyone explain why ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several solutions:

  1. Use typeof. It is a special operator and will never result in a ReferenceError. It evaluates to "undefined" for, well, the undefined value or for a variable which does not exist in context. I'm not a fan of it, but it seems very common.

  2. Use window.jQuery. This forces a "property lookup": property lookups never fail, and return undefined if said property does not exist. I've seen it used in some frameworks. Has the downside of assuming a context (usually window).

  3. Make sure the variable is "declared": var jQuery; if (jQuery) { /* yay */ }. Doesn't seem very common, but it is entirely valid. Note that var is just an annotation and is hoisted. In the global context this will create the "jQuery" property.

  4. Catch the ReferenceError. Honestly, I have never seen this nor do I recommend it, but it would work.

Happy coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...