How to determine whether an object contains a certain attribute in es6

青灯夜游
Release: 2023-01-11 16:25:17
Original
4688 people have browsed it

Two judgment methods: 1. Use the in keyword to detect whether the object has specified attributes. The syntax is "attribute name in object". If true is returned, it is included, otherwise it is not included. 2. Use the hasOwnProperty() function, the syntax is "object.hasOwnProperty (property name)", if true is returned, it is included.

How to determine whether an object contains a certain attribute in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use indexOf(), includes() and other methods to check whether an array contains an element.

So how to check the object? Determine whether an object contains a certain attribute?

Method 1: Use the in keyword

Function: Detect whether the attribute exists in the object. You can use the in keyword to detect whether the current object has the specified attribute.

Syntax:

属性名 in 对象
Copy after login

Determine whether the attribute name exists in the object and return a Boolean value

Example:

const person = { name: '小爱', salary: 23 };
console.log('salary' in person); // true
console.log('sex' in person); // false
Copy after login

How to determine whether an object contains a certain attribute in es6

Method 2: Use the hasOwnProperty() function

You can determine whether the object contains a certain property name and return a Boolean value

对象.hasOwnProperty(属性名)
Copy after login

Example:

const person = { name: '小爱', salary: 23 };
person.hasOwnProperty('salary')
console.log(person.hasOwnProperty('salary')); // true
console.log(person.hasOwnProperty('sex')); // false
Copy after login

How to determine whether an object contains a certain attribute in es6

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to determine whether an object contains a certain attribute in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!