简体   繁体   English

typeof a =='undefined'vs typeof a ==='undefined'

[英]typeof a == 'undefined' vs typeof a === 'undefined'

As I understand the prefered way to check undefined variables is typeof a === 'undefined' . 据我所知,检查未定义变量的首选方法是typeof a === 'undefined'

But why it is better then typeof a == 'undefined' ? 但为什么它更好然后typeof a == 'undefined' In which places can it fail? 它可以在哪些地方失败?

In this instance, since typeof will always give you a string: It isn't better (nor is it worse). 在这种情况下,因为typeof将总是给你一个字符串:它不是更好(也不是更糟)。 It makes no practical difference. 它没有实际的区别。

In general , using === is preferred because it forces you to be explicit about your types and saves you from getting results you don't expect when JavaScript's type resolution rules are unintuitive. 通常 ,使用===是首选,因为它会强制您明确您的类型,并使您无法获得JavaScript的类型解析规则不直观时您不期望的结果。

The difference between == and === is that == performs conversions. =====之间的区别在于==执行转换。 So for instance 1 will be == to '1' but not === to '1' . 所以例如1将是=='1'而不是==='1' The reason why that approach is preferred when you check for undefined is because in JavaScript there are known comparison pitfalls. 当你检查undefined时,首选这种方法的原因是因为在JavaScript中存在已知的比较缺陷。

The most common: 最常见的:

''        ==   '0'           //false
0         ==   ''            //true
0         ==   '0'           //true
false     ==   'false'       //false
false     ==   '0'           //true
false     ==   undefined     //false
false     ==   null          //false
null      ==   undefined     //true
" \t\r\n" ==   0             //true

So with === you are avoiding the null == undefined problem, which can lead to hard-to-find bugs. 因此,使用===您可以避免null == undefined问题,这可能导致难以发现的错误。 That's why you should use == instead of === . 这就是你应该使用==而不是=== Because === is not performing any conversions behind the scenes, it is also a faster operation. 因为===不在幕后执行任何转换,所以它也是一个更快的操作。

In this specific case, it won't make a difference effect-wise. 在这种特定情况下,它不会产生影响。 Whether you use typeof a == 'undefined' or typeof a === 'undefined' the output will be the same, with no bugs. 无论你使用typeof a == 'undefined'还是typeof a === 'undefined' ,输出都是一样的,没有错误。 That's because typeof returns a string. 那是因为typeof返回一个字符串。 However, the operation will be faster, so you have a negligible performance increase. 但是,操作会更快,因此您的性能可以忽略不计。

因为typeof只返回字符串,所以将两个字符串与==进行比较是安全的。

There is a big difference between == and === ( Check out here) =====之间有很大的区别( 点击这里)

But, since typeof will always return string, it's ok to use this. 但是,因为typeof将始终返回字符串,所以可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM