如何检查JavaScript中的对象属性是否未定义?


当前回答

读到这里,我很惊讶我没有看到这一点。我已经找到了多种算法可以解决这个问题。

从未定义

如果从未定义对象的值,那么如果将其定义为null或undefined,则将无法返回true。如果您希望为设置为undefined的值返回true,这很有用

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

定义为未定义或从未定义

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

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

定义为错误值、未定义、空或从未定义。

通常,人们要求我提供一种算法,以确定某个值是否为假值、未定义值或空值。以下工作。

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

其他回答

Object.hasOwnProperty(o,'propertyname');

然而,这并不能通过原型链进行查找。

您可以像这样使用JavaScript对象函数:

var ojb ={
    age: 12
}

if(ojb.hasOwnProperty('name')){
    console.log('property exists and is not undefined');
}

如果获得该属性或该属性未定义,则上述方法返回true。

我不确定将==与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

与void 0进行比较,以获得简洁性。

if (foo !== void 0)

它不像(typeoffoo!=='undefined')那样冗长

在JavaScript中,有truthy和falsy表达式。如果要检查属性是否未定义,可以直接使用给定的If条件,

使用真/假概念。

if(!ob.someProp){
    console.log('someProp is falsy')
}

然而,还有几种方法可以检查对象是否具有属性,但对我来说似乎很长。

使用==未定义的签入if条件

if(ob.someProp === undefined){
    console.log('someProp is undefined')
}

使用的类型

typeof充当未定义值和变量是否存在的组合检查。

if(typeof ob.someProp === 'undefined'){
    console.log('someProp is undefined')
}

使用hasOwnProperty方法

JavaScript对象已在对象原型中的hasOwnProperty函数中构建。

if(!ob.hasOwnProperty('someProp')){
    console.log('someProp is undefined')
}

不深入,但第一种方法看起来很短,对我来说很好。下面是JavaScript中truthy/falsy值的详细信息,未定义的是其中列出的falsy。所以if条件的行为正常,没有任何故障。除了未定义的值之外,值NaN、false(显然)、“”(空字符串)和数字0也是假值。

警告:请确保属性值不包含任何错误值,否则if条件将返回false。对于这种情况,可以使用hasOwnProperty方法