Object.keys
时间: 2023-10-12 19:19:13 浏览: 19
Object.keys 是 JavaScript 中一个用于获取对象自身可枚举属性名称的方法。它返回一个由对象自身可枚举属性名称组成的数组。
例如:
```
const obj = { a: 1, b: 2, c: 3 };
const keys = Object.keys(obj);
console.log(keys); // ["a", "b", "c"]
```
在上面的例子中,Object.keys 方法返回了一个由 obj 对象自身可枚举属性名称 "a"、"b"、"c" 组成的数组。注意,Object.keys 方法不会返回 obj 对象原型链上的属性。如果需要获取原型链上的属性,可以使用 Object.getOwnPropertyNames 方法。
相关问题
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'
```
ts Object.keys
Object.keys 是 TypeScript 中的一个内置函数,用于获取一个对象的所有可枚举属性的键名。它返回一个字符串数组,包含了对象中所有可枚举属性的键名。
使用 Object.keys 的语法如下:
```typescript
Object.keys(obj)
```
其中,obj 是要获取键名的对象。
例如,假设有一个对象 person,它包含了姓名、年龄和性别属性:
```typescript
const person = {
name: 'John',
age: 30,
gender: 'male'
};
```
如果我们想获取 person 对象的所有键名,可以使用 Object.keys:
```typescript
const keys = Object.keys(person);
console.log(keys); // 输出 ['name', 'age', 'gender']
```
这样就可以获取到 person 对象中的所有键名,并将它们存储在 keys 数组中。