The use of the valueof function and the ToString method in JavaScript

Source: Internet
Author: User
Tags javascript array

All JS data types have both the valueof and ToString methods, except for NULL.

The ValueOf function method in JavaScript is to return the original value of the specified object.

How to use:
Object.valueof ().

object is a required parameter and is an arbitrarily intrinsic Javascrip object.


JavaScript's ValueOf () method
The ValueOf () method can return the original value of a Boolean object.
Usage booleanobject.valueof (), the return value is the original Boolean value of Booleanobject. If the object calling the method is not a Boolean, an exception TypeError is thrown.

The code is as follows:


<script type= "Text/javascript" >
var boo = new Boolean (false);
document.write (Boo.valueof ());
</script>


The above script will output false.

the ValueOf method definition differs for each JavaScript intrinsic object .

Object return value
Array The elements of the array are converted to strings, which are separated by commas and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean A Boolean value.
Date The stored time is the number of milliseconds that are counted from midnight January 1, 1970 UTC.
Function function itself.
Number numeric value.
Object The object itself. This is the default condition.
String The string value.

The Math and Error objects do not have a valueOf method.


the ToString () method of the JavaScript Boolean object
The ToString () method converts a logical value to a string and returns the result.
Usage booleanobject.tostring (), which returns the string "true" or "false" based on the original Boolean value or the value of the Booleanobject object. If the object calling the method is not a Boolean, an exception TypeError is thrown.
This method is called automatically when a Boolean object is used in a string environment.
The following script creates a Boolean object and converts it to a string:

The code is as follows:
<script type= "Text/javascript" >
var boo = new Boolean (true);
document.write (Boo.tostring ());
</script>


Script output: True.

the ToString () method of the JavaScript number object

The ToString () method converts a Number object to a string and returns the result. Usage: numberobject.tostring (radix). The return value is a string representation of the number. For example, when Radix is 2 o'clock, Numberobject is converted to a string represented by a binary value. The TypeError exception is thrown when the object calling the method is not number.

Parameters Description
Radix Optional. An integer that specifies the cardinality of the number that makes 2 ~ 36. If this argument is omitted, cardinality 10 is used. Note, however, that if the parameter is a value other than 10, the ECMAScript standard allows the implementation to return any value.
Instance

In this example, we will convert a number to a string:

<script type= "Text/javascript" >var number = new Number (1337);d Ocument.write (number.tostring ()) </script>

Output:

1337
the ToString () method of the JavaScript string Object

The ToString () method returns a string. Syntax: Stringobject.tostring (). Returns the original string value of the value stringobject. This method is not typically called. The TypeError exception is thrown when the object calling the method is not a String.

the ToString () method of the JavaScript array object

The ToString () method converts the array to a string and returns the result. Syntax: Arrayobject.tostring (). The return value is a string representation of arrayobject. The return value is the same as the string returned by the join () method without parameters. When the array is used in a string environment, JavaScript calls this method to automatically convert the array into a string. However, in some cases, you need to explicitly call the method.

Note: The elements in the array are separated by commas.

Instance
<script type= "Text/javascript" >var arr = new Array (3) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" Document.writ E ( arr.toString() ) </script>

Output:

George,john,thomas
the ToString () method of the JavaScript date object

The ToString () method converts a Date object to a string and returns the result. Usage: dateobject.tostring (). The return value is a string representation of dateobject, expressed using local time.

Instance

In this example, we will convert today's date to a string:

<script type= "Text/javascript" >var d = new Date () document.write (d.tostring ()) </script>

Output:

Tue Oct 21:27:54 gmt+0800 (China Standard Time)


let's look at one example :

The code is as follows:

var AAA = {
I:10,
Valueof:function () {return this.i+30;},
Tostring:function () {return this.valueof () +10;}
}
Alert (AAA > 20); True
alert (+AAA); 40
Alert (AAA); 50


This results because they secretly invoke the valueof or ToString method. But how to differentiate which method is called, we can test it by another method. In the Console.log, please experiment with the FF with Firebug!

The code is as follows:


var bbb = {
I:10,
Tostring:function () {
Console.log (' toString ');
return this.i;
},
Valueof:function () {
Console.log (' valueOf ');
return this.i;
}
}
Alert (BBB);//ToString
alert (+BBB); Ten ValueOf
Alert ("+BBB"); Ten ValueOf
Alert (String (BBB)); Ten toString
Alert (number (BBB)); Ten ValueOf
Alert (bbb = = ' 10 '); True ValueOf
Alert (bbb = = = ' 10 '); False


At first glance, it is probably a feeling that if you call the ToString method when converting to a string, the ValueOf method is called if it is converted to a numeric value, but two of them are very discordant. One is alert (' +bbb '), the string should be called the ToString method ... Another we can understand for the time being that the = = = operator does not make implicit conversions, so they are not called. To pursue the truth, we need more rigorous experimentation.

The code is as follows:


var AA = {
I:10,
Tostring:function () {
Console.log (' toString ');
return this.i;
}
}
alert (AA);//ToString
alert (+AA); Ten toString
Alert (' +aa '); Ten toString
Alert (String (AA)); Ten toString
Alert (number (AA)); Ten toString
Alert (aa = = ' 10 '); True toString
Look at valueof again.
var bb = {
I:10,
Valueof:function () {
Console.log (' valueOf ');
return this.i;
}
}
Alert (BB);//[Object Object]
alert (+BB); Ten ValueOf
Alert (' +bb '); Ten ValueOf
Alert (String (BB)); [Object Object]
Alert (number (BB)); Ten ValueOf
Alert (BB = = ' 10 '); True ValueOf
Found a little different?! It is not as uniform as the above ToString. For that [object object], I would expect to inherit from object, and we'll take it out again.
Object.prototype.toString = null;
var cc = {
I:10,
Valueof:function () {
Console.log (' valueOf ');
return this.i;
}
}
Alert (cc);//ValueOf
alert (+CC); Ten ValueOf
Alert (' +cc '); Ten ValueOf
Alert (String (cc)); Ten ValueOf
Alert (number (cc)); Ten ValueOf
alert (cc = = ' 10 '); True ValueOf


If only ToString is overridden, the object conversion ignores the presence of valueof to convert. However, if only the ValueOf method is overridden, the valueof method is preferred when converting to a string. In the case where ToString cannot be called, only valueof can be made to battle. For that strange string stitching problem, it may be that the operator, opened Ecma262-5 found there is a getvalue operation. Well, then the answer should be uncovered. Overrides increase the optimization of their invocation, and in the case of operators, the valueof has a higher priority than the ToString.

The use of the valueof function and the ToString method in JavaScript

Related Article

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.