Object.keys()、Object.values()、Object.entries()详解

In JavaScript, Object.keys()is a built-in function that takes the names of all enumerable properties in an object and returns an array containing those property names.

Here is Object.keys()an example of using the function:

const obj = { a: 1, b: 2, c: 3 };

const keys = Object.keys(obj);
console.log(keys); // 输出: ["a", "b", "c"]

In the above example, we created an objobject named , which contains three properties: a, band c. We then use Object.keys()to get the property names of this object, storing them in an keysarray called . Finally, we print this array to the console, and the output is ["a", "b", "c"].

It should be noted that Object.keys()only the names of enumerable properties are returned, and properties on the prototype chain are not included. If you want to get all properties of an object, including non-enumerable properties and inherited properties, you can use the Object.getOwnPropertyNames()or Reflect.ownKeys()function

Object.values() method returns an array of the given object's own enumerable property values, in the same order (traversing the object from left to right).

Here is Object.values()an example using :

const dictionary = { apple: 'apple', orange: 'orange', banana: 'banana' };

const values = Object.values(dictionary);

console.log(values); // output: ["apple", "orange", "banana"]

Object.entries() The method returns an array of key-value pairs for the given object's own enumerable properties, returned as an array.

Here is Object.entries()an example using :

const dictionary = { apple: 'apple', orange: 'orange', banana: 'banana' };

const entries = Object.entries(dictionary);

console.log(entries); // output: // [ // ["apple", "apple"], // ["orange", "orange"], // ["banana", "banana"] / / ]

Guess you like

Origin blog.csdn.net/kuang_nu/article/details/131783881