Home  >  Article  >  Web Front-end  >  javascript how to convert other types to string

javascript how to convert other types to string

coldplay.xixi
coldplay.xixiOriginal
2021-04-15 13:57:183612browse

Javascript methods to convert other types to string: 1. Use the [tostring()] method; 2. Call the [string()] function; 3. Use implicit conversion.

javascript how to convert other types to string

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Javascript method to convert other types to string:

First method: use tostring() method

The usage method is as follows:

<script type="text/javascript">
var num = 123;
num = num.toString();
//调用xxx的.toString()方法,就是xxx.toString()
</script>

Call the tostring() method of the converted data to convert other types into string

And this method will not affect the original variable, it will return the result

But please note that there is no tostring() method for null and undefined values

If used, an error will be reported

Second method: call string() The function

is used as follows:

<script type="text/javascript">
var obj = null;
obj = String(obj);
//调用string()函数,并将被转换的数据作为参数,传递给函数
</script>

The string() function is similar to the tostring() method,

However, the string() function can convert null and undefined, and The tostring() method cannot be used

The third method: use implicit conversion

Using implicit conversion is actually using operators for conversion. The method is as follows:

<script type="text/javascript">
var obj = null;
obj = obj + "";
// 任何值和字符串做加法,都会将其转换为字符串,而后做拼接
// 可以利用这个特点,将任意数据类型转换为string,只 +""
</script>

This method actually calls the string() function, so it can be converted.

Related free learning recommendations: javascript video tutorial

The above is the detailed content of javascript how to convert other types to string. 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