我想知道以下几点之间的区别(如果有的话):
if( someDOMElement.someProperty )
{
...
if( someDOMElement.someProperty != null )
{
...
if( someDOMElement.someProperty != undefined )
{
...
一个人比其他人更安全吗?
答案 0 :(得分:4)
那些都会做同样的事情,而且其中一个不会比其他人更容易出错。如果您使用的是!==
而不是!=
,那么只有当值null
(第二个)或undefined
(第三个)时,后两个才会成立),因为!==
运算符不执行强制。
Javascript会在与!=
或==
进行比较时强制显示值,例如:
alert(false == 0); // alerts "true"
alert(false === 0); // alerts "false"
===
和!==
运算符可让您控制该行为。强制发生的规则是detailed in the spec(有点复杂),但只是一个简单的“这不是0
,""
,null
或{{1 }}?”可以简单地写undefined
并且效果很好。 if (thingy)
,0
,""
和null
都是“ falsey ”。
Sean Kinsey has a point关于一些主机对象,但我认为大多数(如果不是所有)DOM元素属性都可以。特别是,我已经看到COM对象表现出一些有趣的行为,例如在undefined
评估if (comObject.property)
时评估true
if (comObject.property == null)
。 (在我的例子中,COM对象作为我正在使用的产品的服务器端API的一部分公开;我使用Javascript服务器端以及客户端。)值得注意的是,这可能发生。当你处理Javascript对象和(根据我的经验)DOM对象时,你很好。
答案 1 :(得分:1)
假设someDOMElement不为null,没有特别的区别:
http://www.steinbit.org/words/programming/comparison-in-javascript
如果使用!==
会有所不同答案 2 :(得分:1)
根据someDOMElement
的具体内容,这些结果可能会有非常不同的结果,如果涉及主机对象(例如,实现为ActiveXObjects的对象),它们都不是“安全”的。
您应该使用其中一种方法
// use this if you expect a callable property
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
// use this if you are only looking for a property
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
alert(isHostObject(someDOMElement, "someProperty"))
您可以在http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
了解有关正确功能检测的更多信息答案 3 :(得分:0)
取决于你所谓的价值。
if(someDOMElement && someDOMElement.someProperty !=undefined){
the property exists and has been set to a value other than undefined or null-
it may be 0, false, NaN or the empty string, as well as any truthy value
}