Detecting an undefined object property

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

    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

提交回复
热议问题