On the difference between string () and. ToString () in JS _javascript skill

Source: Internet
Author: User

We know that string () and. ToString () can be converted to string types, but there is a difference between string () and. ToString ().

1. toString () can convert all of the data to a string, but to exclude null and undefined

For example, convert False to String type

<script>
  var str = false.tostring ();
  Console.log (str, typeof str);
</script>

The result returned is false,string

See if null and undefined can be converted to strings

<blockquote style= "margin-right:0px" dir= "ltr" ><pre class= "html" name= "code" ><script>
  var str = null.tostring ();
  Console.log (str, typeof str);
</script>

Result program Error

<script>
  var str = undefined.tostring ();
  Console.log (str, typeof str);
</script>

The program also complains

In the. toString () bracket, you can write a number that represents the system, corresponding to the string

Binary:. toString (2);

Octal system:. toString (8);

Decimal:. toString (10);

Hex:. toString (16);

2, String () can convert null and undefined to strings, but cannot be converted to strings

For example, to convert null to a string

<script>
  var str = String (null);
  Console.log (str, typeof str);
</script>

The result returned is null,string

Convert undefined to string

<script>
  var str = String (undefined);
  Console.log (str, typeof str);
</script>

The result returned is undefined,string

The above is a small series for everyone to talk about the difference between the JS string () and. ToString () All the content, I hope that we support the cloud-Habitat Community ~

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.