Home > Article > Web Front-end > How to access object properties with integer names in JavaScript?
MDN JavaScript documentation states that numeric literals can be used for object property names. However, accessing these properties with standard dot notation (e.g., me.123) may result in errors.
To reference an object property with an integer name, use bracket notation with either square brackets (me[123]) or string quotes (me["123"]).
<code class="javascript">const me = { name: "Robert Rocha", 123: 26, origin: "Mexico", }; console.log(me[123]); // 26 console.log(me["123"]); // 26</code>
Using bracket notation allows JavaScript to interpret the integer name as a string, enabling you to access the property as intended.
Although not recommended, you can still access the properties using a for-in loop, which iterates through all the object's properties, including those with numeric names.
<code class="javascript">for (let key in me) { if (typeof key === "number") { console.log(key, me[key]); } }</code>
The for-in loop provides a more verbose but still functional way of accessing properties with integer names.
The above is the detailed content of How to access object properties with integer names in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!