Home > Web Front-end > JS Tutorial > A brief discussion on the difference between String() and .toString() in JS

A brief discussion on the difference between String() and .toString() in JS

高洛峰
Release: 2016-12-09 15:26:53
Original
1006 people have browsed it

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

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

For example, convert false to string type

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

The returned result is false, string

See if null and undefined can be converted to string

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

As a result, the program reported an error

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

The program also reported 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);

Hex: .toString(16);

2. String() can convert null and undefined into strings, But there is no way to convert into a string

For example, if you convert null to a string

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

, the result returned is null, string

convert undefined to a string

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

The result returned is undefined, string


Related labels:
js
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