怎么检查JavaScript对象上是否存在一个属性?

目录
文章目录隐藏
  1. 1. 真值检查
  2. 2. in 操作符
  3. 3. hasOwnProperty()
  4. 总之

在 JavaScript 中,有几种方法可以检查对象上是否存在一个属性。选择哪种方法在很大程度上取决于实际需求,所以需要我们了解每种方法的工作原理。

让我们来看看最常用的几种方法。

1. 真值检查

const myObj = {
  a: 1,
  b: 'some string',
  c: [0],
  d: {a: 0},
  e: undefined,
  f: null,
  g: '',
  h: NaN,
  i: {},
  j: [],
  deleted: 'value'
};

delete myObj.deleted;

console.log(!!myObj['a']); // 1, true
console.log(!!myObj['b']); // 'some string', true
console.log(!!myObj['c']); // [0], true
console.log(!!myObj['d']); // {a: 0}, true
console.log(!!myObj['e']); // undefined, false
console.log(!!myObj['f']); // null, false
console.log(!!myObj['g']); // '', false
console.log(!!myObj['h']); // NaN, false
console.log(!!myObj['i']); // {}, true
console.log(!!myObj['j']); // [], true
console.log(!!myObj['deleted']); // false

正如你所看到的,这导致了几个假值的问题,所以使用这种方法时要非常小心。

2. in 操作符

如果一个属性存在于一个对象或其原型链上,in 操作符返回 true。

const myObj = {
  someProperty: 'someValue',
  someUndefinedProp: undefined,
  deleted: 'value'
};

delete myObj.deleted;

console.log('someProperty' in myObj); // true
console.log('someUndefinedProp' in myObj); // true
console.log('toString' in myObj); // true (inherited)
console.log('deleted' in myObj); // false

in 操作符不会受到假值问题的影响。然而,它也会对原型链上的属性返回 true。这可能正是我们想要的,如果我们不需要对原型链上对属性进行判断,可以使用下面这种方法。

3. hasOwnProperty()

hasOwnProperty()继承自Object.HasOwnProperty()。和 in 操作符一样,它检查对象上是否存在一个属性,但不考虑原型链。

const myObj = {
  someProperty: 'someValue',
  someUndefinedProp: undefined,
  deleted: 'value'
};

delete myObj.deleted;

console.log(myObj.hasOwnProperty('someProperty')); // true
console.log(myObj.hasOwnProperty('someUndefinedProp')); // true
console.log(myObj.hasOwnProperty('toString')); // false
console.log(myObj.hasOwnProperty('deleted')); // false

不过要注意的一点是,并不是每个对象都继承自 Object。

const cleanObj = Object.create(null);
cleanObj.someProp = 'someValue';
// TypeError: cleanObj.hasOwnProperty is not a function
console.log(cleanObj.hasOwnProperty('someProp'));

如果遇到这种罕见的情况,还可以按以下方式使用。

const cleanObj = Object.create(null);
cleanObj.someProp = 'someValue';
console.log(({}).hasOwnProperty.call(cleanObj,'someProp')); // true

总之

这三种方法都有其适合使用的场景,重要的是需要我们要熟悉它们的区别,这样才能选择最好的一种,以便让我们的代码能够按照期望运行。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 怎么检查JavaScript对象上是否存在一个属性?

发表回复