Analysis of methods for converting a value to a string in JavaScript []_javascript techniques

Source: Internet
Author: User
Tags readable

Translator Note: The first two days in the ES5 to see the time a problem, see this article today, just explain very clearly, translated a bit.
In JavaScript, there are three main ways to convert any value to a string. This article explains each of these methods and their pros and cons.

1. Three methods of converting strings
The three ways to convert value to a string are:

1.value.tostring ()
2. "" + Value
3.String (value)

The problem with the first approach is that it cannot convert null and undefined into strings. There are also the second and third methods, the effect of which is essentially the same.

• "" "+value: Using the addition operator with an empty string can convert any value to a string, and I find the code of this method very readable, but there are some people who prefer to use this type of conversion rather than string (value).
string (Value): This method is more readable, and the only problem is that this function call can confuse some people, especially those familiar with Java, because String is also a constructor. Note that it behaves differently as a normal function and as a constructor :

Copy Code code as follows:

> String ("abc") = = = new String ("abc")
False

> typeof String ("abc")
' String '
> String ("abc") instanceof string
False

> typeof new String ("abc")
' Object '
> New String ("abc") instanceof string
True


string as a normal function produces a string (a raw value). As a constructor, an instance of a string object is generated. The latter is rarely used in JavaScript, so basically you can ignore string as a constructor, But be sure to remember that it is a conversion function.

2. Nuances of "" "+value and String (value)
By now you know it. Both + and string () can convert their arguments to strings. But there are subtle differences in the way they are converted, but in almost all cases the results are the same.

2.1 Convert the original value to a string
Both of these methods use the ToString () operation inside the engine to convert the original value to a string. " Internal operation means: This operation function is defined in ECMAScript 5.1 (§9.8), but the ES language itself does not have access to it. The following table explains how ToString () transforms the original value.



Parameters Results
Undefined "Undefined"
Null "NULL"
Boolean value "true" or "false"
Digital Numbers as strings, such as "1.765"
String No conversion required

2.2 Converting an object value to a string

Both methods convert the object value to the original value before converting the original value to a string. But in this transformation, + uses the internal toprimitive (number) operation (unless the Date object is converted), and string () is toprimitive ( String).

toprimitive (number): Converts an object value to the original value and first invokes obj.valueof (). If the return value is an original value, the original value is returned. If not, then call Obj.tostring (). If the return value is a raw value, Returns the original value. Otherwise, throw the TypeError exception.
toprimitive (String): Similar to the previous method, just call the Obj.tostring () method preferentially instead of obj.valueof ().
By converting the following object, you can see the difference between them:
Copy Code code as follows:

var obj = {
Valueof:function () {
Console.log ("valueof");
return {}; is not the original value, continue execution
},
Tostring:function () {
Console.log ("toString");
return {}; is not the original value, continue execution
}
};

Run:
> "" + obj
valueof
Tostring
Typeerror:cannot Convert object to primitive value

> String (obj)
Tostring
valueof
Typeerror:cannot Convert object to primitive value

2.3 Results are usually the same
The differences mentioned above are hardly likely to be met in real life. Because: most objects use the default inherited ValueOf () method, which always returns the value of the object itself.

Copy Code code as follows:

> var x = {}
> x.valueof () = = X
True


Therefore, toprimitive (number) usually skips the return value of the ValueOf method return the ToString () method, which behaves exactly like Toprimitive (String). But if this object is a Boolean, Number or an object instance of string, its valueof () returns an original value (the original value before the object is wrapped). Then these two operations are performed as follows:

toprimitive (number) Returns the result of the return value of the object's ValueOf () method (the original value before being wrapped) after the ToString () operation.
toprimitive (String) returns the return value of the object's ToString () method (the return value of the ToString () operation on the original value before the object is wrapped).
In this way, they return the same result, but the way of conversion is different.

3. Conclusion

Which way do you choose to convert other types of values to strings? If you can make sure that the value is never null or undefined, you can convert it using value.tostring (). Otherwise, "" "+value and string (value) can be selected , I think string (value) is a little more specific.

4. Related articles

    1. JavaScript Values:not Everything is a object [difference between original value and object value]
    2. What is {} + {} in JavaScript? [explains how the + operator works]
    3. string concatenation in JavaScript [how to better connect multiple strings]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.