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

How to Access JavaScript Object Properties with Hyphens?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 18:15:18980browse

How to Access JavaScript Object Properties with Hyphens?

Accessing JavaScript Object Properties with Hyphens

When working with JavaScript, referencing object properties with a hyphen can be challenging. Consider the following scenario:

var style = css($(this));
alert(style.width); // Works fine
alert(style.text-align); // Uncaught Reference Error

The hyphen in "text-align" is interpreted as a minus sign, leading to the error.

Solution 1: Camel Case Conversion

For CSS properties, using the camel case key notation is the preferred method:

obj.style-attr // Becomes

obj["styleAttr"]

Solution 2: Key Notation

You can also use key notation instead of dot notation:

style["text-align"]

JavaScript allows you to refer to object properties using the same syntax as arrays:

arr[0] // Array index

obj["method"] // Object property

Additional Considerations:

  • Properties accessed with key notation are evaluated as strings.
  • Characters not allowed in JavaScript variables must be accessed using key notation.
  • The following regular expression outlines valid property names:
[a-zA-Z_$][0-9a-zA-Z_$]*

By utilizing these techniques, you can efficiently access JavaScript object properties containing hyphens.

The above is the detailed content of How to Access JavaScript Object Properties with Hyphens?. 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