Home  >  Article  >  Web Front-end  >  Introduction to object conversion functions toString() and valueOf()

Introduction to object conversion functions toString() and valueOf()

PHP中文网
PHP中文网Original
2017-05-25 14:49:182063browse

In JavaScript, the operation of converting object to boolean is very simple: all objects are true after being converted to boolean; even objects such as new Boolean(false) are still true after being converted to boolean.

Copy code The code is as follows:

var x = new Boolean(false);if(x){  console.log("x is true");}

When converting object to string or number, JavaScript will call two conversions of object Functions: toString() and valueOf().

toString()

The toString() function is to return the string representation of object. The default toString() method of object in JavaScript returns a string "[object Object]". When defining a class, you can implement the 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 date objects:

1.array’s toString() method will return comma-separated Array members. For example, [1,2,3].toString() will return the string "1,2,3".

2. The toString() method of function will return the text definition of the function. For example, (function(x){return x*2;}).toString() will return the string "function(x){return x*2;}".

3.RegExp’s toString() method is similar to function’s toString() method and will return the text definition of the regular expression. For example, /d /g.toString() will return the string "/\d /g".

4.Date’s toString() method will return a readable date and time string.

valueOf()

The valueOf() function is to return the numerical representation of the object. The default valueOf() method of object in JavaScript will return the object itself. Like toString(), you can implement a new valueOf() method when defining a class to return the desired result. JavaScript defines a more readable valueOf() method for the Date object:

The valueOf() method of Date will return a value, which is the time difference between the Date object and 0:00 on January 1, 1970 (in milliseconds).

Related recommendations]

1. Detailed explanation of valueOf method examples in java

2. Between valueOf and toString, (String) in Java The difference between

3. Usage of tostring() and valueof() and the difference between the two_

4.valueOf function and toString In-depth understanding of the method

5. The difference between valueOf, parseInt, and toString in Java

6. Using the toString() method to return the time is String

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn