Object.keys()
时间: 2023-10-12 17:17:11 浏览: 156
`Object.keys()` 是一个 JavaScript 方法,它返回一个给定对象自身可枚举属性(不包括继承的属性)的数组。这个数组的元素是这些属性的 key 值。例如:
```javascript
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // ["a", "b", "c"]
```
在上面的例子中,`keys`是一个数组,它包含了对象`obj`中所有的 key 值。`Object.keys()`方法常用于遍历对象属性或检查一个对象是否为空。
相关问题
Object.keys
Object.keys() is a method in JavaScript that returns an array of a given object's own property names. It takes the object as an argument and returns an array of strings containing the property names. The order of the property names in the array is the order in which they were added to the object. The method does not include any properties from the object's prototype chain.
object.keys
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'
```
阅读全文