Home > Article > Web Front-end > Why Can\'t You Add Properties to String Primitives in JavaScript?
Why Attempting to Add Properties to String Primitives Fails
In JavaScript, attempts to add properties to string primitives, such as the code below, will be ineffective:
<code class="javascript">var test = "test"; test.test = "test inner"; console.log(test.test); // Output: undefined</code>
Types in JavaScript
To understand this issue, one must grasp the concept of types in JavaScript. There are eight types in JavaScript:
Primitive values (e.g., strings) cannot possess properties, while objects can.
Property Assignment
When assigning a property to a variable, such as:
<code class="javascript">foo.bar = 'abc';</code>
The result depends on the value of foo:
Solution for Sorting Dates
In your specific case, since dates are stored as strings, one workaround for sorting dates is to use a custom comparison function in your sorting algorithm that assumes dates are always stored in the same format. This custom function can perform a date-aware comparison based on the format of the date strings.
The above is the detailed content of Why Can\'t You Add Properties to String Primitives in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!