"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access Object Properties with Numeric Names in JavaScript?

How to Access Object Properties with Numeric Names in JavaScript?

Published on 2024-12-21
Browse:762

How to Access Object Properties with Numeric Names in JavaScript?

Referencing Object Properties with Numeric Names

Despite the documentation's suggestion that object literal property names can be integers, accessing these properties using the dot syntax (e.g., me.123) fails.

Alternative Syntax: Array-Style Access

To access an object property with an integer name, you must use the array-style syntax:

  • me[123]

This syntax behaves as if the property were an element of an array, with 123 being the index.

String Notation

Alternatively, you can use string notation to access the property:

  • me["123"]

This approach encloses the integer in double quotes, treating it as a string.

Example:

In your example, you can access the property with integer name 123 using:

console.log(me[123]); // Output: 26
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3