Home > Web Front-end > JS Tutorial > How to Access Object Properties with Space Characters in JavaScript?

How to Access Object Properties with Space Characters in JavaScript?

Barbara Streisand
Release: 2024-11-19 05:17:03
Original
638 people have browsed it

How to Access Object Properties with Space Characters in JavaScript?

Accessing Objects with Space Characters in JavaScript

When working with JavaScript objects, accessing properties with space characters in their names can be challenging. Consider the following object:

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

Accessing the property 'comic' is straightforward: myTextOptions.cartoon.comic. However, attempting to access the property 'kid' using various dot syntax fails:

myTextOptions.character names.kid
myTextOptions."character names".kid
myTextOptions.character\ names.kid
myTextOptions.'character names'.kid
myTextOptions.["character names"].kid
myTextOptions.character%20names.kid
Copy after login

The solution lies in utilizing ECMAScript's "bracket notation":

myTextOptions[ 'character names' ].kid;
Copy after login

Bracket notation allows you to access object properties with space characters or any other special characters by enclosing the property name in square brackets. This notation can be used both for reading and writing properties efficiently in such scenarios.

For further information on working with objects in JavaScript, please refer to the following resource:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

The above is the detailed content of How to Access Object Properties with Space Characters 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