Get the App
SLTechnology News&Howtos  ›  Development  › 

How to choose Reflect.ownKeys () and Object.keys ()

Shulou Source: shulou.com Published: 2022-06-03 04:46:52 10月26日 Update

This article mainly explains "how to choose Reflect.ownKeys () and Object.keys ()". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to choose Reflect.ownKeys () and Object.keys ()".

Consider a question: how to traverse the Keys of Object in JavaScript and encounter the two methods of Reflect.ownKeys (obj) and Object.keys (obj), what is the difference between them?

Let's first look at an example:

Const obj = {a: 5, b: 5}; console.log (Reflect.ownKeys (obj)); console.log (Object.keys (obj)); / / Result / / ['asides,' b'] / / ['asides,' b']

It doesn't seem to be any different. Go through the documents of the two methods and learn:

Object.keys (obj) returns an array of enumerable properties of a given object in the same order that property names are returned when traversing the object in a normal loop.

The result returned by Reflect.ownKeys (obj) is equivalent to:

Object.getOwnPropertyNames (target) .concat (Object.getOwnPropertySymbols (target))

The Object.getOwnPropertyNames () method returns an array of property names of all its own properties of the specified object, including properties that cannot be enumerated but do not include symbol values as names.

The Object.getOwnPropertySymbols () method returns an array of all the Symbol properties of a given object itself.

Reflect.ownKeys (obj) equals to returning all the properties of a given object as an array.

Let's see the difference through the following code:

Var testObject = {[Symbol ('1')]: 1, a: 2}; Object.defineProperty (testObject, 'myMethod', {value: function () {alert ("Non enumerable property");}, enumerable: false}); console.log (Object.keys (testObject)); / / [' a'] console.log (Reflect.ownKeys (testObject); / / ['asides,' myMethod', Symbol (1)]

Summary

Object.keys (obj): the result is all enumerable key on object

Reflect.ownKeys (obj): the result is all key.

Thank you for your reading, the above is the content of "how to choose Reflect.ownKeys () and Object.keys ()". After the study of this article, I believe you have a deeper understanding of how to choose Reflect.ownKeys () and Object.keys (), and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Attributes objects arrays selections methods results learning two content questions order different consistent nothing code examples names that is differences ideas Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Huawei NVidia Shulou Tech Info Linux