Home > Web Front-end > JS Tutorial > body text

About the difference between String() and .toString() in JS (combined with the code, it is clear at a glance)

亚连
Release: 2018-05-18 14:05:39
Original
1770 people have browsed it

The following is the difference between String() and .toString() in JS that I have compiled for you. Interested students can take a look.

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

1. .toString() can convert all data into strings, but null and undefined must be excluded.

For example, convert false to string type

<script>  
    var str = false.toString();  
    console.log(str, typeof str);  
</script>
Copy after login

The result returned is false, string

See if null and undefined can be converted into strings

<script>  
    var str = null.toString();  
    console.log(str, typeof str);  
</script>
Copy after login

As a result, the program reports an error

<script>  
    var str = undefined.toString();  
    console.log(str, typeof str);  
</script>
Copy after login

The program also reports an error

.toString() You can write a number in the brackets, representing the base, corresponding to the base string

Binary: .toString(2);

Octal: .toString(8);

Decimal: .toString(10);

Hexadecimal: .toString(16);

2. String() can convert null and undefined into strings, but there is no way Convert to hexadecimal string

For example, convert null to string

<script>  
    var str = String(null);  
    console.log(str, typeof str);  
</script>
Copy after login

The returned result is null, string

Convert undefined to string

<script>  
    var str = String(undefined);  
    console.log(str, typeof str);  
</script>
Copy after login

The returned result is undefined, string

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles: Steps to use the created method in

vue.js

##Key value characters Detailed explanation of the steps to convert string to json string

js Detailed explanation of the use of key-value pairs stored in

The above is the detailed content of About the difference between String() and .toString() in JS (combined with the code, it is clear at a glance). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!