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"".
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);
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);
Method 3: For any data type""
var a = 123; a = a + ""; console.log(a); console.log(typeof a);
[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!