Home >Web Front-end >Front-end Q&A >How to determine whether an object contains a certain attribute in es6
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.
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
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
[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!