Home > Web Front-end > JS Tutorial > How to force value type to string in javascript

How to force value type to string in javascript

青灯夜游
Release: 2022-02-16 16:52:17
Original
4513 people have browsed it

Forced conversion method: 1. Call the toString() method with the syntax "data object to be converted.toString()"; 2. Call the String() function with the syntax "String (data to be converted)"; 3. Use the " " character to splice strings, and the syntax is "data to be converted"".

How to force value type to string in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Forced type conversion refers to forcing one data type to another data type. Generally refers to converting other data types into String, Number, and Boolean.

Let’s talk about the method of forcing the value type to be converted to String.

Convert to String type

There are three ways to convert other values ​​​​to strings: toString(), String(), and string.

Method 1: Call the toString() method of the converted data type

This method will not affect the original variable, it will return the conversion result, but please note : The two values ​​​​null and undefined do not have toString() methods. If their methods are called, an error will be reported.

var a = 123;
a = a.toString();
console.log(a);
console.log(typeof a);
Copy after login

Method 2: Call the String() function and pass the converted data as a parameter to the function

When using the String() function for forced type conversion, For Number and Boolean, the toString() method is actually called, but for null and undefined, the toString() method will not be called. It will directly convert null to "null" and undefined directly to "undefined".

var a = 123;
a = String(a);
console.log(a);
console.log(typeof a);

var b = undefined;
b = String(b);
console.log(b);
console.log(typeof b);

var c = null;
c = String(c);
console.log(c);
console.log(typeof c);
Copy after login

Method 3: For any data type""

var a = 123;
a = a + "";
console.log(a);
console.log(typeof a);
Copy after login

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to force value type to string in javascript. 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