检查jQuery中是否未定义和null

时间:2013-02-21 06:27:43

标签: javascript jquery ternary-operator

在检查是否为null或未定义以及我是否应该使用!==!=和“undefined”或未定义时,我有点困惑。

以下是我正在处理的一些代码。我的null / unudefined等在哪里出错?

var c = (jQuery(this).prop("target") != null && jQuery(this).prop("target") != undefined && jQuery(this).prop("target").toLowerCase() == "_blank") ? 1 : 0;

由于

7 个答案:

答案 0 :(得分:11)

一般来说,保持简单。

要检查undefined,请使用:

foo === undefined
foo !== undefined

要检查null,请使用:

foo === null
foo !== null

要同时检查,请使用:

foo == null
foo != null

无论如何,将.prop()存储到变量中以保持其清洁。但在您的情况下,如果它等于"_blank",那么您知道它不是nullundefined,所以:

var targ = jQuery(this).prop("target").toLowerCase();

var c = targ === "_blank" ? 1 : 0;

或者你可以通过将boolean强制转换为number来缩短时间:

var targ = jQuery(this).prop("target").toLowerCase();

var c = +(targ === "_blank");

最后两个解决方案是安全的,因为.prop()将始终返回string

答案 1 :(得分:5)

  • nullundefined都是" falsy"值,因此可以检查它们是否为布尔值。因此,与nullundefined相比没有任何意义,除非您需要知道它们是否是这样的值。

  • 比较时,最好使用严格比较(例如===!==等)

  • 条件中的&&如果前面的条件是" falsy"则不评估以下条件。

  • You don't even need jQuery,因为this是您的DOM对象(可能是<a>)并且您正在尝试获取target属性:

最后:

var c = (this.target && this.target.toLowerCase() === "_blank") ? 1 : 0;

答案 2 :(得分:1)

这是检查undefined的最佳方法:

if(typeof variable_here != 'undefined'){
   // your code here.
 };

这是检查null的最佳方法:

if(variable_here !== null){
       // your code here.
     };

所以你的代码应该是这样的:

var c = (jQuery(this).prop("target") !== null && typeof jQuery(this).prop("target") !== 'undefined' && jQuery(this).prop("target").toLowerCase() == "_blank") ? 1 : 0;

答案 3 :(得分:0)

由于undefined是变量类型,因此请使用typeof

var c = (
 $(this).attr("target") != NULL && 
 typeof $(this).attr("target") != "undefined" && 
 $(this).attr("target").toLowerCase() == "_blank"
) ? 1 : 0;
但是,我认为你只需要最后一次检查。目标"_blank"c必须为1,否则为0。如果target被设定是否真的重要?

此外,使用attr()方法获取属性,因为prop()适用于selectedIndextagName等属性。

答案 4 :(得分:0)

只检查一个值,不要获得相同的属性3次。

var c = 0;
var prop = $(this).prop("target");
if(prop && prop.toLowerCase() === "_blank") c = 1;

答案 5 :(得分:0)

我有这样的东西,这与你的问题无关,但会帮助你

var targ = jQuery(this).prop("target").toLowerCase();

现在,如果你想检查targ是null还是undefined

 var c = (!targ || "") ? 1 : 0

希望这会对你有所帮助

答案 6 :(得分:0)

在JavaScript中,由于以下原因,您无需显式检查变量是否为null或未定义:

  1. null或undefined在布尔表达式中返回false。

  2. JS表达式从左到右求值。因此对于|| b,如果a为假,则将仅评估b。但是,如果a为true,则不会检查b。类似地,对于&& b,如果a为假,则不会计算b。

因此,如果if(a!= null){“做某事”}可以写成(a){“做某事”}或只是&&“做某事”。

以相同的方式,当该值设置为null或未定义时,可用于设置默认值:

function someFunction(age){
    var age= age|| 18;
}

参考:https://codereview.stackexchange.com/questions/472/usage-of-the-ternary-operator-with-functions-listening-to-click-events