Introduction to object conversion functions toString () and valueOf () in JavaScript, tostringvalueof
In JavaScript, object conversion to boolean is very simple: all objects are true after being converted to boolean; even objects like new Boolean (false) are still true after being converted to boolean.
Copy codeThe Code is as follows:
Var x = new Boolean (false );
If (x ){
Console. log ("x is true ");
}
When converting an object to a string or number, JavaScript calls two conversion functions of the object: toString () and valueOf ().
ToString ()
The toString () function returns the string representation of the object. The default toString () method of the object in JavaScript returns the string "[object Object]". When defining a class, you can implement a new toString () method to return more readable results. JavaScript defines a more readable toString () method for array objects, function objects, regular expression objects, and Date objects:
1. The toString () method of array returns an array member separated by commas. For example, [, 3]. toString () returns the string ", 3 ″.
2. The function's toString () method returns the text definition of the function. For example, (function (x) {return x * 2;}). toString () returns the string "function (x) {return x * 2 ;}".
3. The toString () method of RegExp is similar to the toString () method of function. The text definition of the regular expression is returned. For example,/\ d +/g. toString () returns the string "/\ d +/g ".
4. The toString () method of Date returns a readable Date and Time string.
ValueOf ()
The valueOf () function is used to return the value of an object. The default valueOf () method of an object in JavaScript returns the object itself. Like toString (), a new valueOf () method can be implemented when a class is defined to return the required results. JavaScript defines a more readable valueOf () method for the Date object:
1. the valueOf () method of Date returns a value, which is the time difference between the Date object and the on January 1, January 1, 1970 (in milliseconds ).