object.keys
时间: 2023-09-14 22:12:09 浏览: 89
Object.keys() is a built-in JavaScript method that returns an array of the object's property names. It takes an object as an argument and returns an array of the property names of that object. The returned array contains only the property names that are directly owned by the object and not inherited from its prototype chain. The order of the property names in the array is not guaranteed and may vary depending on the JavaScript engine.
For example, consider the following object:
```
const person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
email: 'john.doe@example.com'
};
```
We can use Object.keys() to get an array of the property names of the person object:
```
const keys = Object.keys(person);
console.log(keys); // Output: ['firstName', 'lastName', 'age', 'email']
```
We can then use this array to loop through the object's properties, or access a specific property using bracket notation:
```
keys.forEach(key => {
console.log(person[key]); // Output: 'John', 'Doe', 30, 'john.doe@example.com'
});
console.log(person[keys[0]]); // Output: 'John'
```
阅读全文