如何检查变量或对象是否未定义? [英] How to check if a variable or object is undefined?

查看:159
本文介绍了如何检查变量或对象是否未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以为我可以通过比较未定义的var来检查未定义的var,但这是我在chrome控制台中得到的错误:

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 :

如何检查对象jQuery未定义?

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

编辑:

如果(jQuery)也给我带来问题

if(jQuery) is giving me problems too

编辑:

解决方案:

if(window.jQuery) 有效。
typeof(jQuery)=='undefined'也可以。

有人可以解释原因吗? / p>

Could anyone explain why ?

推荐答案

有几种解决方案:


  1. 使用 typeof 。它是一个特殊的运算符,永远不会产生 ReferenceError 。对于上下文中不存在的变量,它的 undefined 评估为undefined。我不喜欢它,但它似乎很常见。

  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.

使用 window.jQuery 。这会强制进行属性查找:属性查找永远不会失败,如果所述属性不存在,则返回 undefined 。我已经看到它在某些框架中使用过。假设上下文(通常是窗口)的缺点。

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).

确保变量是声明的 : var jQuery; if(jQuery){/ * yay * /} 。似乎并不常见,但它完全有效。请注意, var 只是一个注释并被提升。在全局上下文中,这将创建jQuery属性。

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.

捕获 ReferenceError 。老实说,我从来没有见过这个,也不推荐它,但它会起作用。

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

快乐编码。

这篇关于如何检查变量或对象是否未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆