在JavaScript中测试undefined

Aut*_*cus 2 javascript javascript-events

我只想在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";
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在这里测试undefined?

Pet*_*ley 6

When using undefined as a string you need to do so with the typeof operator.

Also, you should be checking if it's defined before any other checks on the property.

if ( 'undefined' != typeof arguments[0].recordCount && arguments[0].recordCount > 0 )
Run Code Online (Sandbox Code Playgroud)

  • stakx:没有.`typeof`保证返回一个字符串,你将它的返回值与另一个字符串进行比较,所以无论你可能学到什么Crockfordian习惯,它总是没问题:) (4认同)