Home > Web Front-end > JS Tutorial > body text

How do you access object properties with numeric names in JavaScript?

Linda Hamilton
Release: 2024-11-02 15:22:03
Original
388 people have browsed it

How do you access object properties with numeric names in JavaScript?

Accessing Object Properties with Numeric Names

While JavaScript objects typically use string literals as property names, it's possible to utilize integers as well. As mentioned in the MDN documentation:

Additionally, you can use a numeric or string literal for the name of a property.

However, accessing such properties using the standard dot notation (e.g., me.123) can lead to errors.

Solution: Using Bracket Notation

To access an object property with an integer name, you must use bracket notation instead. This involves enclosing the property name within square brackets, like so:

me[123]
Copy after login

Alternatively, you can use bracket notation with string literals:

me["123"]
Copy after login

Both methods will yield the value associated with the property named 123.

Example:

Consider the following object:

me = {
    name: "Robert Rocha",
    123: 26,
    origin: "Mexico"
};
Copy after login

To access the property named 123, you would use:

console.log(me[123]); // Output: 26
Copy after login

Additional Notes:

It's generally not recommended to use integers as object property names, as it can make code harder to read and maintain. However, in certain cases, it may be necessary or convenient to do so.

The above is the detailed content of How do you access object properties with numeric names in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!