Detecting an undefined object property

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

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

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:25

    Reading through this, I'm amazed I didn't see this. I have found multiple algorithms that would work for this.

    Never Defined

    If the value of an object was never defined, this will prevent from returning true if it is defined as null or undefined. This is helpful if you want true to be returned for values set as undefined

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

    Defined as undefined Or never Defined

    If you want it to result as true for values defined with the value of undefined, or never defined, you can simply use === undefined

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

    Defined as a falsy value, undefined,null, or never defined.

    Commonly, people have asked me for an algorithm to figure out if a value is either falsy, undefined, or null. The following works.

    if(obj.prop == false || obj.prop === null || obj.prop === undefined) {
        console.log("The value is falsy, null, or undefined");
    }
    

提交回复
热议问题