测验

如何检查对象是否具有特定属性?

主题
JavaScript

TL;DR

要检查对象是否具有特定属性,可以使用 in 运算符、hasOwnProperty 方法或 Object.hasOwn()in 运算符检查自有属性和继承属性,而后两种方法仅检查自有属性。自 ES2022 起,建议使用 Object.hasOwn(),因为它也能安全地处理无原型对象。

const obj = { key: 'value' };
// 使用 `in` 运算符
if ('key' in obj) {
console.log('Property exists');
}
// 使用 `hasOwnProperty`
if (obj.hasOwnProperty('key')) {
console.log('Property exists');
}

如何检查对象是否具有特定属性?

使用 in 运算符

in 运算符检查属性是否存在于对象中,包括对象原型链中的属性。

const obj = { key: 'value' };
if ('key' in obj) {
console.log('Property exists');
}

使用 hasOwnProperty

hasOwnProperty 方法检查属性是否直接存在于对象上,而不是在其原型链中。

const obj = { key: 'value' };
if (obj.hasOwnProperty('key')) {
console.log('Property exists');
}

使用 Object.hasOwn()

Object.hasOwn()(ES2022 引入)是检查自有属性的推荐方式。与 obj.hasOwnProperty() 不同,它适用于通过 Object.create(null) 创建的无原型对象,也适用于覆盖了 hasOwnProperty 方法的对象。

const obj = { key: 'value' };
if (Object.hasOwn(obj, 'key')) {
console.log('Property exists');
}
const bare = Object.create(null);
bare.key = 'value';
console.log(Object.hasOwn(bare, 'key')); // true

inhasOwnPropertyObject.hasOwn() 之间的区别

  • in 运算符检查自有属性和继承属性。
  • hasOwnPropertyObject.hasOwn() 仅检查自有属性,但 Object.hasOwn() 对无原型对象和覆盖该方法的对象更安全。

具有继承属性的示例

const parentObj = { inheritedKey: 'inheritedValue' };
const childObj = Object.create(parentObj);
childObj.ownKey = 'ownValue';
console.log('inheritedKey' in childObj); // true
console.log(childObj.hasOwnProperty('inheritedKey')); // false
console.log('ownKey' in childObj); // true
console.log(childObj.hasOwnProperty('ownKey')); // true

延伸阅读

在GitHub上编辑