Home >Web Front-end >JS Tutorial >About the difference between String() and .toString() in JS (combined with the code, it is clear at a glance)

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

亚连
亚连Original
2018-05-18 14:05:391798browse

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>

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>

As a result, the program reports an error

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

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>

The returned result is null, string

Convert undefined to string

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

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!

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