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

How to Access JavaScript Object Properties with Hyphens?

Susan Sarandon
Release: 2024-12-10 18:15:18
Original
1009 people have browsed it

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
Copy after login

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"]
Copy after login

Solution 2: Key Notation

You can also use key notation instead of dot notation:

style["text-align"]
Copy after login

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

arr[0] // Array index

obj["method"] // Object property
Copy after login

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_$]*
Copy after login

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!

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