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


当前回答

在最近的JavaScript版本中,引入了新的链接运算符,这可能是检查属性是否存在的最佳方法,否则它将给您提供未定义的

参见下面的示例

  const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

我们可以替换这个旧语法

if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}

使用更简洁的语法

if( response?.data?.someData?.someMoreData) {}

IE、Opera、safari和samsund android不支持此语法

有关详细信息,请查看此URL

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

其他回答

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

if (foo !== void 0)

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

if (somevariable == undefined) {
  alert('the variable is not defined!');
}

您也可以将其转换为函数,如下所示:

function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}

如果使用的是Angular:

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

Undercore.js:

_.isUndefined(obj) 
_.isUndefined(obj.prop) 

查看注释,对于那些想同时检查两者的人来说,它是未定义的还是其值为空:

//Just in JavaScript
var s; // Undefined
if (typeof s == "undefined" || s === null){
    alert('either it is undefined or value is null')
}

如果您使用的是jQueryLibrary,那么jQuery.isEmptyObject()将足以满足这两种情况,

var s; // Undefined
jQuery.isEmptyObject(s); // Will return true;

s = null; // Defined as null
jQuery.isEmptyObject(s); // Will return true;

//Usage
if (jQuery.isEmptyObject(s)) {
    alert('Either variable:s is undefined or its value is null');
} else {
     alert('variable:s has value ' + s);
}

s = 'something'; // Defined with some value
jQuery.isEmptyObject(s); // Will return false;

我使用if(this.variable)来测试它是否被定义。一个简单的if(变量),在前面的答案中推荐,对我来说失败了。

事实证明,只有当变量是某个对象obj.someField的字段时,它才能工作,以检查它是否在字典中定义。但我们可以使用this或window作为字典对象,因为任何变量都是当前窗口中的字段,正如我所理解的那样。因此,这里有一个测试:

如果(this.abc)警报(“已定义”);其他的警报(“未定义”);abc=“abc”;如果(this.abc)警报(“已定义”);其他的警报(“未定义”);

它首先检测到变量abc未定义,并在初始化后定义。