Home  >  Article  >  Web Front-end  >  How to access object properties with integer names in JavaScript?

How to access object properties with integer names in JavaScript?

DDD
DDDOriginal
2024-11-02 07:17:02308browse

How to access object properties with integer names in JavaScript?

Referencing Object Properties with Integer Names

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.

Solution: Bracket Notation

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.

For-In Loop Alternative

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!

Statement:
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