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]
Alternatively, you can use bracket notation with string literals:
me["123"]
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" };
To access the property named 123, you would use:
console.log(me[123]); // Output: 26
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!