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


当前回答

我在这里为那些希望得到奇怪答案的人提供了三种方法:

函数为Undefined1(val){尝试{值a;}捕获(e){返回/未定义/测试(e.message);}return false;}函数为Undefined2(val){回来val&&val+“”==“未定义”;}函数未定义3(val){常量defaultVal={};return((input=defaultVal)=>input==defaultVal(val);}功能测试(func){console.group(`test start:`+func.name);console.log(func(未定义));console.log(func(null));console.log(函数(1));console.log(函数(“1”));console.log(函数(0));console.log(func({}));console.log(func(函数(){}));console.groupEnd();}测试(isUndefined1);测试(未定义2);测试(未定义3);

未定义1:

尝试获取输入值的属性,并检查错误消息(如果存在)。如果输入值未定义,则错误消息将为Uncaught TypeError:无法读取未定义的属性“b”。

未定义2:

将输入值转换为字符串以与“undefined”进行比较,并确保其为负值。

未定义3:

在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");
}

同样的事情也可以写得更短:

if (!variable){
    // Do it if the variable is undefined
}

or

if (variable){
    // Do it if the variable is defined
}

在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方法

在ECMAScript 6中引入,我们现在可以使用代理以一种新的方式处理未定义。它可以用于为任何不存在的财产设置默认值,这样我们就不必每次都检查它是否实际存在。

var handler = {
  get: function(target, name) {
    return name in target ? target[name] : 'N/A';
  }
};

var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)

将输出以下文本而不会得到任何未定义。

Name: Kevin , Age: N/A , Gender: N/A

解决方案不正确。在JavaScript中,

null == undefined

将返回true,因为它们都“强制”为布尔值,并且都为false。正确的方法是检查

if (something === undefined)

这是身份运算符。。。