Home  >  Article  >  Web Front-end  >  How do you access JavaScript object properties with spaces in their keys?

How do you access JavaScript object properties with spaces in their keys?

DDD
DDDOriginal
2024-11-11 01:21:03394browse

How do you access JavaScript object properties with spaces in their keys?

Accessing JavaScript Objects with Spaced Keys

When declaring JavaScript objects, key names can contain spaces, but accessing them using the dot notation (e.g., myObject.child) can be challenging.

Problem:

Accessing properties of JavaScript objects with keys containing spaces, such as "character names" in the given object:

var myTextOptions = {
  'cartoon': {
     comic: 'Calvin & Hobbes',
     published: '1993'
  },
  'character names': {
    kid: 'Calvin',
    tiger: 'Hobbes'
  }
};

Solution:

To access such properties, use ECMAScript's "bracket notation":

myTextOptions[ 'character names' ].kid;

The bracket notation allows you to use strings or expressions to access properties, resolving space issues. It works for both reading and writing object properties.

Additional Information:

  • For more comprehensive information on working with JavaScript objects, refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

The above is the detailed content of How do you access JavaScript object properties with spaces in their keys?. 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