检查对象是否具有

检查对象是否具有

本文介绍了javascript:检查对象是否具有特定元素或属性的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个:

var person = { "name": "John Doe", "email": "[email protected]" };

这个对象只有两个元素,称为nameemail.有些人也有一个元素 age,但这个特定的人没有.检查此问题的最佳方法是什么?

This object only has two elements called name and email. Some persons also have an element age, but this particular person doesn't. What's the best way to check this?

  • if (person.age) { ... }
  • if (person.age != undefined) { ... }
  • if (person.age !== undefined) { ... }
  • if (typeof(person.age) != 'undefined') { ... }
  • if (person.hasOwnProperty('age')) { ... }

我知道所有这些都不一样,例如if (person.age) 也会失败,如果 age does 存在但它是 falsenull''0.我想知道是否有些人不只是完全错误.

I know all these don't do the same, e.g. if (person.age) would also fail if age does exist but it's false or null or '' or 0. And I wonder if some aren't just flat out wrong.

请注意,person 在这里已知是一个现有对象,但 person.age 可能存在也可能不存在.

Note that person is known to be an existing object here, but person.age may or may not exist.

推荐答案

让我们来看看这些检查对象是否具有某个元素或属性的方法的可靠性:

Let's check the reliability of these ways of checking if object has a certain element or property:

如果 Boolean(person.age)false

if (person.age) { ... }

如果 person.agenullundefined

if (person.age != undefined) { ... }

如果 person.ageundefined

if (person.age !== undefined) { ... }
if (typeof(person.age) != 'undefined') { ... }

另一方面,hasOwnProperty() 方法返回一个 boolean 指示对象是否具有指定的属性作为自己的(非继承的)属性.所以它不依赖于 person.age 属性的值.所以这是最好的方式

On the other hand, the hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property. So It does not depend on the value of person.age property. So it is the best way here

if (person.hasOwnProperty('age')) { ... }

如果你想进一步检查一个对象是否有一个可迭代的属性(所有属性包括自己的属性以及继承的属性),那么使用 for..in 循环将给你想要的结果.

If you want to go further and check if an object has a property on it that is iterable(all properties including own properties as well as the inherited ones) then using for..in loop will give you the desired result.

这篇关于javascript:检查对象是否具有特定元素或属性的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:43