Home > Article > Web Front-end > 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' } };
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
The solution lies in utilizing ECMAScript's "bracket notation":
myTextOptions[ 'character names' ].kid;
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!