Detecting an undefined object property

后端 未结 30 2938
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  鱼传尺愫
    2020-11-21 05:27

    All the answers are incomplete. This is the right way of knowing that there is a property 'defined as undefined':

    var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){
      return ((prop in obj) && (typeof obj[prop] == 'undefined'));
    };
    

    Example:

    var a = { b : 1, e : null };
    a.c = a.d;
    
    hasUndefinedProperty(a, 'b'); // false: b is defined as 1
    hasUndefinedProperty(a, 'c'); // true: c is defined as undefined
    hasUndefinedProperty(a, 'd'); // false: d is undefined
    hasUndefinedProperty(a, 'e'); // false: e is defined as null
    
    // And now...
    delete a.c ;
    hasUndefinedProperty(a, 'c'); // false: c is undefined
    

    Too bad that this been the right answer and is buried in wrong answers >_<

    So, for anyone who pass by, I will give you undefined's for free!!

    var undefined ; undefined ; // undefined
    ({}).a ;                    // undefined
    [].a ;                      // undefined
    ''.a ;                      // undefined
    (function(){}()) ;          // undefined
    void(0) ;                   // undefined
    eval() ;                    // undefined
    1..a ;                      // undefined
    /a/.a ;                     // undefined
    (true).a ;                  // undefined
    

提交回复
热议问题