检测未定义的对象属性

JavaScript

小宇宙Near

2020-03-09

检查JavaScript中的对象属性是否为最佳方法是undefined什么?

第167篇《检测未定义的对象属性》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

13个回答
阿飞Harry小胖 2020.03.09

From lodash.js.

var undefined;
function isUndefined(value) {
  return value === undefined;
}

It creates a LOCAL variable named undefined which is initialized with the default value -- the real undefined, then compares value with the variable undefined.


Update 9/9/2019

I found lodash updated its implementation. See my issue and the code.

To be bullet-proof, simply use:

function isUndefined(value) {
  return value === void 0;
}
神无老丝Davaid 2020.03.09

If you are using Angular:

angular.isUndefined(obj)
angular.isUndefined(obj.prop)

Underscore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 
GilPro 2020.03.09

I use if (this.variable) to test if it is defined. Simple if (variable), recommended above, fails for me. It turns out that it works only when variable is a field of some object, obj.someField to check if it is defined in the dictionary. But we can use this or window as the dictionary object since any variable is a field in current window, as I understand it. Therefore here is a test

if (this.abc) alert("defined"); else alert("undefined");

abc = "abc";
if (this.abc) alert("defined"); else alert("undefined");

It first detects that variable abc is undefined and it is defined after initialization.

Itachi阳光 2020.03.09

The solution is incorrect. In JavaScript,

null == undefined

will return true, because they both are "casted" to a boolean and are false. The correct way would be to check

if (something === undefined)

which is the identity operator...

木嘢 2020.03.09

读完这个,我很惊讶我没看到这个。我发现有多种算法可以解决此问题。

从未定义

如果从未定义对象的值,true则如果将其定义为null,这将防止返回undefined如果您希望为设置为的值返回true,这将很有帮助。undefined

if(obj.prop === void 0) console.log("The value has never been defined");

定义为未定义或从未定义

如果您希望其结果以true的值定义undefined,或者从未定义,则可以简单地使用=== undefined

if(obj.prop === undefined) console.log("The value is defined as undefined, or never defined");

定义为虚假值,未定义,空值或从未定义。

通常,人们要求我提供一种算法来判断值是伪造的undefined还是null以下作品。

if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
    console.log("The value is falsy, null, or undefined");
}
神奇逆天猪猪 2020.03.09

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

米亚凯 2020.03.09
"propertyName" in obj //-> true | false
L泡芙Jim 2020.03.09

在《探索JavaScript中的Null和Undefined的深渊》一文中,我读到诸如Underscore.js之类的框架使用此函数:

function isUndefined(obj){
    return obj === void 0;
}
阳光西里小哥 2020.03.09

我没有看到(希望我没有错过它)有人在属性之前检查对象。因此,这是最短和最有效的(尽管不一定最清晰):

if (obj && obj.prop) {
  // Do something;
}

如果obj或obj.prop未定义,为null或为“ falsy”,则if语句将不执行代码块。通常是大多数代码块语句(在JavaScript中)所需的行为。

卡卡西逆天十三 2020.03.09

我不确定用===with 的来源是哪里typeof,并且按照惯例我会在许多库中使用它,但是typeof运算符返回字符串文字,而且我们很早就知道,所以为什么还要输入也检查一下吗?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient
米亚小小神乐 2020.03.09
if ( typeof( something ) == "undefined") 

这对我有用,而其他人则没有。

番长村村 2020.03.09

我相信对此主题有许多不正确的答案。与通常的看法相反,“未定义” 不是 JavaScript中的关键字,实际上可以为其分配值。

正确的代码

执行此测试的最可靠方法是:

if (typeof myVar === "undefined")

这将始终返回正确的结果,甚至可以处理myVar未声明的情况

简并代码。不使用。

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("You have been misled. Run away!");
}

此外,myVar === undefined在未声明myVar的情况下将引发错误。

西门樱前端 2020.03.09

在JavaScript中有且有不确定的它们具有不同的含义。

  • 未定义表示尚未定义变量值;目前尚不清楚该值是多少。
  • null表示已定义变量值并将其设置为null(无值)。

Marijn Haverbeke在他的免费在线书“ Eloquent JavaScript ”(强调我的)中指出

还有一个相似的值null,其含义是“已定义此值,但没有值”。undefined和null之间的含义差异主要是学术上的,通常不是很有趣。在实际程序中,通常需要检查某些东西是否“有价值”。在这些情况下,可以使用表达式something == undefined,因为即使它们的值不完全相同,null == undefined也会产生true。

因此,我想检查是否未定义的最好方法是:

if (something == undefined)

希望这可以帮助!

编辑:响应您的编辑,对象属性应该以相同的方式工作。

var person = {
    name: "John",
    age: 28,
    sex: "male"
};

alert(person.name); // "John"
alert(person.fakeVariable); // undefined

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android