问题
Suppose I have this:
var person = { "name": "John Doe", "email": "john.doe@example.com" };
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')) { ... }
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.
Note that person
is known to be an existing object here, but person.age
may or may not exist.
回答1:
Let's check the reliability of these ways of checking if object has a certain element or property:
This can fail if Boolean(person.age)
is false
if (person.age) { ... }
This can fail if person.age
is null
or undefined
if (person.age != undefined) { ... }
These can fail if person.age
is undefined
if (person.age !== undefined) { ... }
if (typeof(person.age) != 'undefined') { ... }
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')) { ... }
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.
回答2:
You could use Object.hasOwnProperty()
. Check out documentation here.
回答3:
You can use hasOwnProperty to check particular key or property present or not.
var person = { "name": "John Doe", "email": "john.doe@example.com" };
console.log(person.hasOwnProperty('age')) //false
var person = { "name": "John Doe", "email": "john.doe@example.com", "age": 18 };
console.log(person.hasOwnProperty('age')) //true
if you use (person.age) it will give you false if the value is false or empty or null even the age property is present and has own property check property is present or not
来源:https://stackoverflow.com/questions/46425072/javascript-best-way-of-checking-if-object-has-a-certain-element-or-property