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


当前回答

我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}

其他回答

在最近的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

回顾

许多给定的答案给出了错误的结果,因为它们没有区分对象属性不存在的情况和属性值未定义的情况。以下是最流行的解决方案的证明:

让obj={a: 666中,u: undefined//“u”属性的值为“undefined”//“x”属性不存在}console.log('>>>好结果:');console.log('A',obj中的“u”,obj的“x”);console.log('B',obj.hasOwnProperty(“u”),obj.hasOwnProperty(“x”));console.log('\n>>>坏结果:');console.log('C',obj.u==未定义,obj.x==未确定);console.log('D',obj.u==未定义,obj.x==未定义);console.log('E',obj[“u”]==未定义,obj'“x”]===未定义);console.log('F',obj[“u”]==未定义,obj'“x”]===未定义);console.log('G',!obj.u,!obj.x);console.log('H',对象类型u=='未定义',对象的类型x=='不定义');

检查属性值是否为未定义的特殊值的通常方法是:

if(o.myProperty === undefined) {
  alert("myProperty value is the special value `undefined`");
}

要检查对象是否实际上没有这样的属性,并且当您尝试访问它时,默认情况下会返回undefined:

if(!o.hasOwnProperty('myProperty')) {
  alert("myProperty does not exist");
}

要检查与标识符关联的值是否为未定义的特殊值,或者该标识符是否尚未声明:

if(typeof myVariable === 'undefined') {
  alert('myVariable is either the special value `undefined`, or it has not been declared');
}

注意:最后一个方法是引用未声明的标识符而不出现早期错误的唯一方法,这与值为undefined不同。

在ECMAScript 5之前的JavaScript版本中,全局对象上名为“undefined”的属性是可写的,因此,如果不小心重新定义了foo==undefineed,则简单的检查可能会出现意外的行为。在现代JavaScript中,属性是只读的。

然而,在现代JavaScript中,“undefined”不是关键字,因此函数内部的变量可以命名为“undefine”,并隐藏全局属性。

如果您担心这种(不太可能的)边缘情况,可以使用void运算符获取特殊的未定义值本身:

if(myVariable === void 0) {
  alert("myVariable is the special value `undefined`");
}

检查是否存在密钥的一种简单方法是:

if (key in obj) {
  // Do something
} else {
  // Create key
}

const obj = {
  0: 'abc',
  1: 'def'
}

const hasZero = 0 in obj

console.log(hasZero) // true

我很惊讶我还没有看到这个建议,但它比使用typeof测试更具特异性。如果您需要知道对象属性是用undefined初始化的还是从未初始化过,请使用Object.getOwnPropertyDescriptor():

// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');

if (typeof descriptor === 'undefined') {
  // was never initialized
} else if (typeof descriptor.value === 'undefined') {
  if (descriptor.get || descriptor.set) {
    // is an accessor property, defined via getter and setter
  } else {
    // is initialized with `undefined`
  }
} else {
  // is initialized with some other value
}