2010-07-22 37 views
2

我只想在argument[0].recordCount大于零或未定义的情况下运行代码。但是,当argument[0].recordCound警报显示未定义时,会运行代码。在JavaScript中未定义的测试

if(arguments[0].recordCount > 0 && 
    arguments[0].recordCount !== 'undefined') 
{ //if more than 0 records show in bar 

    document.getElementById('totalRecords').innerHTML = 
     arguments[0].recordCount + " Records"; 
} 

我该如何测试未定义的?

回答

6

当使用undefined作为字符串,您需要使用typeof运算符执行此操作。

此外,你应该检查它是否定义之前任何其他检查属性。

if ('undefined' != typeof arguments[0].recordCount && arguments[0].recordCount > 0) 
+0

+1。应该使用'!=='运算符来代替'!='? – stakx 2010-07-22 18:28:59

+4

stakx:没有。'typeof'保证返回一个字符串,并且你将它的返回值与另一个字符串进行比较,所以无论你学到什么Crockfordian习惯,它都会很好。 – 2010-07-22 18:33:13

+0

@stakx - 无关紧要。 'typeof'返回一个字符串。 – 2010-07-22 18:58:29

2

undefined关键字恒定值一个全局变量,使用不带引号:

if(arguments[0].recordCount > 0 && arguments[0].recordCount !== undefined) 

但实际上这将是足以测试只有第一个条件:

if(arguments[0].recordCount > 0) 

因为如果recordCount大于零,则仍然定义它。


更常见的是切换条件和测试第一是否被定义,以避免在下面的测试可能出现的错误(不知道这是必要这里):

if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0) 
+0

对,如果你坚持把它比作一个“串”,就用'!='而不是'!=='。前者只是测试值,而后者测试**都是类型和价值。 – BalusC 2010-07-22 18:14:27

+0

'undefined'不是JavaScript中的关键字。但是,如果'x'未定义,'typeof(x)'将返回字符串'“undefined”'。 – stakx 2010-07-22 18:24:04

+1

@stakx:谢谢你澄清。 – 2010-07-22 18:29:17

1

要检查一个变量是不是空,不是不确定的,

if(thatVariable)足够,虽然隐式转换可以为某些情况下,thatVariable为空字符串或布尔值,或数字0引起的问题。如果隐式转换是不是我们变的情况下,下面会做,

if(arguments[0].recordCount && arguments[0].recordCount > 0) 

但是,下面的的问题,

if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0) 

考虑,

var undefined = 'surprise' //possible since undefined is not a keyword 
if(arguments[0].recordCount !== undefined && arguments[0].recordCount > 0) 

现在,这个 '如果' 将打破,即使总记录是不确定的。

还有一件事:if(a != null)也会由于隐式转换而检查未定义。因此if(a != null && a != undefined)是多余的

相关问题