Detecting an undefined object property

后端 未结 30 2922
花落未央
花落未央 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

    'if (window.x) { }' is error safe

    Most likely you want if (window.x). This check is safe even if x hasn't been declared (var x;) - browser doesn't throw an error.

    Example: I want to know if my browser supports History API

    if (window.history) {
        history.call_some_function();
    }
    

    How this works:

    window is an object which holds all global variables as its members, and it is legal to try to access a non-existing member. If x hasn't been declared or hasn't been set then window.x returns undefined. undefined leads to false when if() evaluates it.

    0 讨论(0)
  • 2020-11-21 05:27

    You can get an array all undefined with path using the following code.

     function getAllUndefined(object) {
    
            function convertPath(arr, key) {
                var path = "";
                for (var i = 1; i < arr.length; i++) {
    
                    path += arr[i] + "->";
                }
                path += key;
                return path;
            }
    
    
            var stack = [];
            var saveUndefined= [];
            function getUndefiend(obj, key) {
    
                var t = typeof obj;
                switch (t) {
                    case "object":
                        if (t === null) {
                            return false;
                        }
                        break;
                    case "string":
                    case "number":
                    case "boolean":
                    case "null":
                        return false;
                    default:
                        return true;
                }
                stack.push(key);
                for (k in obj) {
                    if (obj.hasOwnProperty(k)) {
                        v = getUndefiend(obj[k], k);
                        if (v) {
                            saveUndefined.push(convertPath(stack, k));
                        }
                    }
                }
                stack.pop();
    
            }
    
            getUndefiend({
                "": object
            }, "");
            return saveUndefined;
        }
    

    jsFiddle link

    0 讨论(0)
  • 2020-11-21 05:27

    Here is my situation:

    I am using the result of a REST call. The result should be parsed from JSON to a JavaScript object.

    There is one error I need to defend. If the arguments to the REST call were incorrect as far as the user specifying the arguments wrong, the REST call comes back basically empty.

    While using this post to help me defend against this, I tried this:

    if( typeof restResult.data[0] === "undefined" ) { throw  "Some error"; }
    

    For my situation, if restResult.data[0] === "object", then I can safely start inspecting the rest of the members. If undefined then throw the error as above.

    What I am saying is that for my situation, all the previous suggestions in this post did not work. I'm not saying I'm right and everyone is wrong. I am not a JavaScript master at all, but hopefully this will help someone.

    0 讨论(0)
  • 2020-11-21 05:27

    ECMAScript 10 introduced a new feature - optional chaining which you can use to use a property of an object only when an object is defined like this:

    const userPhone = user?.contactDetails?.phone;
    

    It will reference to the phone property only when user and contactDetails are defined.

    Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 05:28

    The usual way to check if the value of a property is the special value undefined, is:

    if(o.myProperty === undefined) {
      alert("myProperty value is the special value `undefined`");
    }
    

    To check if an object does not actually have such a property, and will therefore return undefined by default when you try and access it:

    if(!o.hasOwnProperty('myProperty')) {
      alert("myProperty does not exist");
    }
    

    To check if the value associated with an identifier is the special value undefined, or if that identifier has not been declared. Note: this method is the only way of referring to an undeclared (note: different from having a value of undefined) identifier without an early error:

    if(typeof myVariable === 'undefined') {
      alert('myVariable is either the special value `undefined`, or it has not been declared');
    }
    

    In versions of JavaScript prior to ECMAScript 5, the property named "undefined" on the global object was writeable, and therefore a simple check foo === undefined might behave unexpectedly if it had accidentally been redefined. In modern JavaScript, the property is read-only.

    However, in modern JavaScript, "undefined" is not a keyword, and so variables inside functions can be named "undefined" and shadow the global property.

    If you are worried about this (unlikely) edge case, you can use the void operator to get at the special undefined value itself:

    if(myVariable === void 0) {
      alert("myVariable is the special value `undefined`");
    }
    
    0 讨论(0)
提交回复
热议问题