JavaScript中如何测试未定义的变量

4

如果argument[0].recordCount大于零或未定义,则我希望运行代码。然而,当argument[0].recordCound弹出未定义时,代码仍会运行。

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";
}

在这里,我该如何测试未定义变量?

3个回答

7

在将undefined用作字符串时,您需要使用typeof运算符。

此外,在对属性进行任何其他检查之前,应该检查它是否已定义。

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

+1. 可能应该使用 !== 运算符而不是 != - stakx - no longer contributing
4
stakx: no. typeof保证返回一个字符串,而您正在将其返回值与另一个字符串进行比较,因此无论您学习了什么Crockfordian的习惯,它始终都会很好 :) - Tim Down
@stakx - 不相关。typeof 返回一个字符串。 - Peter Bailey
1
@Tim:你说得对。每当我看到==!=时,我就会认为应该使用严格的运算符。 - stakx - no longer contributing
可能相关的性能比较:typeof var=== undefined(后者比前者更快)。http://jsperf.com/type-of-undefined-vs-undefined - msanford

3

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)

如果你坚持将其视为“字符串”进行比较,那么请使用 != 而不是 !==。前者只测试值,而后者则测试 类型和值 - BalusC
在 JavaScript 中,undefined 不是 关键字。但是,如果 x 是未定义的,则 typeof(x) 将返回字符串 "undefined" - stakx - no longer contributing
undefined 可以被更改。你不应该与它进行比较。如果在比较时不能保证 recordCount 有某个值,那么程序就会出错。 - lincolnk

1

要检查一个变量不是null和undefined,

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”语句会中断,即使recordCount未定义。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接