Differentiate the ToString (), tolocalestring (), ValueOf () methods in JavaScript

Source: Internet
Author: User

First we randomly create an object, which is very simple, open the FF browser's firebug switch to the console or open the WebKit browser's review element feature.

Enter the following:

  

var obj1=[1,2,3,4,5]var obj2=[5,4,3,2,1]var obj3=[obj1,obj2] 

Then try calling Obj3 's ToString (), tolocalestring (), ValueOf () method:

Depending on the output, the contents of the ToString () and toLocaleString () method outputs are found to be the same, and both are in string form. And the valueof output is the value of the object itself.

Think about it, the people who develop JavaScript will never be bored to create two of the same ways.

Let's change obj1 and obj2 a little bit, one more time:

What did you find? toLocaleString () is not the same as what ToString accesses: toLocaleString accesses the toLocaleString () method of each element in Obj3, ToString accesses the ToString () method of each element in Obj3.

So why is ToString () and tolocalesting () separated? Very simple, from the method name can be known, the ToString () method gets a string (traditional string), and toLocaleString () Method gets the Localestring (local environment string).

If you are developing scripts that are used worldwide, use the ToString () method to convert objects into strings.

Because Localestring () returns a string based on the local environment of your machine, the symbols that it and the values returned by ToString () will change subtly in the different local environments.

So using ToString () is an insurance method that returns a unique value, which does not change due to changes in the local environment.

It is recommended to use localestring () if it is to return data of a time type. If you are working with strings in the background, be sure to use ToString ().

Differentiate the ToString (), tolocalestring (), ValueOf () methods in JavaScript

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.