Home > Article > Web Front-end > The usage of tostring() and valueof() and the difference between them
Basically, all JS data types have two methods, valueOf and toString, except null. The two of them solve the problem of javascript value operation and display.
1. The usage is as follows:
toString() method: Returns the string representation of the object.
Object | Operation |
---|---|
Array | Convert the elements of Array is a string. The resulting strings are comma separated and concatenated. |
Boolean | If the Boolean value is true, return "true". Otherwise, returns "false". |
Date | Returns the text representation of the date. |
Error | Returns a string containing the relevant error message. |
Function | returns a string in the following format, where functionname is the name of the called toString method function: function functionname( ) { [native code] } |
Number | Returns the text representation of the number. |
String | returns the value of the String object. |
Default | returns "<span style="font-family:NSimsun">[object objectname]</span> ", where <span style="font-family:NSimsun">objectname</span> is the name of the object type. |
valueOf() method: Returns the original value of the specified object.
Object | Return Value |
---|---|
Array | The elements of the array are converted to strings, these Strings are separated by commas and concatenated together. Its operation is the same as the Array.toString and Array.join methods. |
Boolean | Boolean value. |
Date | The time stored is the number of milliseconds since midnight on January 1, 1970 UTC. |
Function | The function itself. |
Number | Number value. |
Object | The object itself. This is the default. |
String | String value. |
2. Common points and differences between the two:
Common points: In JavaScript, the toString() method and The valueOf() method is automatically called when outputting the object.
The difference: when the two coexist, in numerical operations, valueOf is called first, and in string operations, toString is called first.
Related recommendations]
1. Detailed explanation of valueOf method examples in java
2. Between valueOf and toString, (String) in Java The difference between
3.The difference between valueOf, parseInt and toString in Java
4. In-depth understanding of valueOf function and toString method
5. Introduction to ’s object conversion functions toString() and valueOf()