2011-12-16 98 views
6

我一直以为我可以通过比较不确定的检查未定义的变种,但是这是我在Chrome控制台出现错误:如何检查变量或对象是否未定义?

enter image description here

如何如何检查为对象的jQuery是未定义?

编辑:

enter image description here

如果(jQuery的)是给我的问题太

编辑:

解决方案:

if(window.jQuery)作品。 typeof(jQuery) == 'undefined'也可以。

任何人都可以解释为什么?

+0

[http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object-is-undefined/8531076#8531076][1] [1]:http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object-is-undefined/8531076#8531076 – 2011-12-16 07:40:22

+0

HTTP:// stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript,http://stackoverflow.com/questions/8531059/how-to-check-if-a-variable-or-object- is-undefined – 2011-12-16 07:49:47

回答

9

有几种解决方案:

  1. 使用typeof。这是一个特殊的操作员,绝不会导致ReferenceError。对于在上下文中不存在的变量,其值undefined的评估为“未定义”。我不是它的粉丝,但它似乎很常见。使用。这会强制执行“属性查找”:属性查找永不失败,如果该属性不存在,则返回undefined。我已经看到它在一些框架中使用。假设背景有缺点(通常为window)。

  2. 确保该变量为“声明”:var jQuery; if (jQuery) { /* yay */ }。似乎并不常见,但它完全有效。请注意,var只是一个注释并已悬挂。在全球范围内,这将创建“jQuery”属性。

  3. 赶上ReferenceError。老实说,我从来没有见过这个,也不推荐它,但它会工作。

快乐编码。

2

据我知道你能行

if(typeof X == 'undefined') 

但也有资源,你可能想看看装载机。我面前的答案也是正确的。

-1

if(jQuery)应该够了,不是吗?

+0

不会。它可能会抛出一个ReferenceError(上面的内容在帖子中)。 – 2011-12-16 07:26:55

3

here

if(typeof jQuery == "undefined") { 
    document.write("undefined"); 
}else{ 
    document.write("Exists"); 
} 
+0

虽然这个“作弊”与`var test = 1`,因为上下文是不一样的:)但它仍然是有效的这种情况没有它,但。 – 2011-12-16 08:01:06

5

流程1:

if (jQuery) { 
    // jQuery is loaded 
} else { 
    // jQuery is not loaded 
} 

流程2:

if (typeof jQuery == 'undefined') { 
    // jQuery is not loaded 
} else { 
    // jQuery is loaded 
} 
1

在你的代码名为 “jQuery的” 变量从未宣布,所以它会抛出一个错误,如“xxx(变量名称)未定义”。

可以使用typeof运算符来检查是一个变量未定义或不

if (typeof(jQuery) == "undefined")