Home > Web Front-end > JS Tutorial > How to determine whether a JS object has a certain attribute

How to determine whether a JS object has a certain attribute

高洛峰
Release: 2017-02-08 17:29:00
Original
1089 people have browsed it

Whether the JS object has a certain attribute

Two methods, but slightly different

1, in operator

var obj = {name:'jack'};
alert('name' in obj); // --> true
alert('toString' in obj); // --> true
Copy after login

It can be seen that whether it is name or toString on the prototype chain, it can be detected and returned true.

2. hasOwnProperty method

var obj = {name:'jack'};
obj.hasOwnProperty('name'); // --> true
obj.hasOwnProperty('toString'); // --> false
Copy after login

The properties inherited from the prototype chain cannot be detected by hasOwnProperty and return false.

It should be noted that although in can detect the properties of the prototype chain, for in usually cannot.

Of course, after rewriting the prototype, for in will be visible under IE9/Firefox/Safari/Chrome/Opera. See: Defects of for in

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

For more related articles on how to determine whether a JS object has a certain attribute, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template