Home  >  Article  >  Web Front-end  >  How to determine whether an object contains a certain attribute in es6

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

青灯夜游
青灯夜游Original
2022-05-19 17:21:194773browse

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 对象

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

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(属性名)

Example:

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

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!

Statement:
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