代码之家  ›  专栏  ›  技术社区  ›  Konrad

有效性测试

  •  3
  • Konrad  · 技术社区  · 16 年前

    我想知道以下两者之间的区别(如果有的话):

    if( someDOMElement.someProperty )
    {
    ...
    
    if( someDOMElement.someProperty != null )
    {
    ...
    
    if( someDOMElement.someProperty != undefined )
    {
    ...
    

    一个比另一个安全吗?

    4 回复  |  直到 16 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    这些都会做同样的事情,其中一个不会比另一个更容易出错。但是如果你使用 !== 而不是 != ,第二个值只有在 null (第二个)或 undefined (第三个),因为 != 运算符不执行强制。

    在与 != == 例如:

    alert(false == 0);   // alerts "true"
    alert(false === 0);  // alerts "false"
    

    这个 === != 操作员允许您控制该行为。强制执行的规则是 detailed in the spec (有点复杂),但只是一个简单的“这件事不是吗? 0 , "" , 无效的 未定义 “可以简单地写 if (thingy) 而且效果很好。 , , 无效的 未定义 都是“ 法西 “。

    肖恩金赛 has a point 关于一些主机对象,尽管我认为大多数(如果不是全部)DOM元素属性都可以。特别是,我见过COM对象表现出一些有趣的行为,例如 if (comObject.property) 评价 true 什么时候 if (comObject.property == null) 评价 . (在我的例子中,它是作为我使用的产品的服务器端API的一部分公开的COM对象;我使用的是JavaScript服务器端和客户端。)值得注意的是,这可能会发生。当你处理javascript对象和(在我的经验中)dom对象时,你很好。

        2
  •  1
  •   mamoo    16 年前

    假设somedomElement不是空的,则没有特殊的区别:

    http://www.steinbit.org/words/programming/comparison-in-javascript

    如果你用的话会有区别的!=

        3
  •  1
  •   Sean Kinsey    16 年前

    完全取决于什么 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

        4
  •  0
  •   kennebec    16 年前

    取决于你所说的值。

    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
    }