Home >Web Front-end >JS Tutorial >How to convert javascript variables to strings
Methods to convert js variables to strings: 1. Use the "value.toString()" statement. toString() can convert js values (except null and undefined) into strings; 2. Use "" "value" statement; 3. Use the "String(value)" statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
The 3 methods of javascript converting variables into strings are as follows:
value.toString()
"" value
String(value)
When value is null or undefined, the first method will not work. . And method 2 and method 3 are basically the same.
"" value:
Convert value to a string by adding it to the empty string. This method is actually a slightly obscure technique that may make it difficult for others to understand the developer's intentions. However, this is a matter of opinion, and some people prefer this method.
String(value): This method is very clear: use the String()
function to convert value to a string. However, String()
has two different uses, which is easy to confuse, especially for Java developers. When String()
is used as a constructor together with operator new, it returns a newly created String object; when String()
is called without new operator, it only value is converted into a raw string. The two are very different:
> String("Fundebug") === new String("Fundebug") false > typeof String("Fundebug") 'string' > String("Fundebug") instanceof String false > typeof new String("Fundebug") 'object' > new String("Fundebug") instanceof String true
In fact, using String()
as a constructor is uncommon, so just use it to convert strings.
<span style="color: #ff0000"><strong>“”Subtle difference between value</strong></span>
and String(value)
"" value
and String(value)
can convert value into a string. How do they do it? In fact, although their results are the same, their methods are slightly different.
Convert the primitive basic type to a string
Both methods use the internal functionToString()
Convert the primitive Basic types are converted to strings. ToString()
The function is defined in ECMAScript 5.1 (§9.8), but cannot be used directly, so it is called an internal function. The following table shows how the ToString()
function converts primitive primitive types to strings:
Parameters | Result |
---|---|
undefined | "undefined" |
"null" | |
"true" or "false" | |
Convert a number to a string, For example: "1.765" | |
No need to convert |
The above is the detailed content of How to convert javascript variables to strings. For more information, please follow other related articles on the PHP Chinese website!