All languages have the ability to convert types, and JavaScript is no exception. It also provides developers with a large number of type conversion access methods. Through global functions, more complex data types can be implemented.
The code copy is as follows:
var a = 3;
var b = a + 3;
var c = "student" + a;
var d = a.toString();
var e = a + "";
document.write(typeof(a) + " " + typeof (b) + " " + typeof (c) + " " + typeof (d) + " " + typeof (e));
//Output number number string string string
The simplest example of type conversion
The code copy is as follows:
var a=b=c=d=e=4;
var f = a+b+c+d+c.toString();
document.write(f);<br>// Output result 164
For converting data types into strings, use toString() JavaScript to convert them into strings and implement mechanism conversion.
The code copy is as follows:
var a =111;
document.writeln(a.toString(2)+"<br>");
document.writeln(a.toString(3)+"<br>");
document.writeln(a.toString(8)+"<br>");
document.writeln(a.toString(10)+"<br>");
document.writeln(a.toString(16)+"<br>");
//Execution results
//
1101111
11010
157
111
6f
String to numerical type, JavaScript uses parseInt() and parseFloat() to convert. Just like the name of the method, the former converts characters into integers, and the latter converts characters into floating point numbers. Only characters can be used to transfer these two methods, otherwise it will be converted to NaN. No more operations are performed.
parseInt() first checks the character at subscript 0. If this character is a valid character, checks the character at 1. If it is not a valid character, terminates the conversion. The following example is an example of parseInt()
The code copy is as follows:
document.writeln(parseInt("4555.5544")+"<br>");
document.writeln(parseInt("0.5544")+"<br>");
document.writeln(parseInt("1221abes5544")+"<br>");
document.writeln(parseInt("0xc")+"<br>");//Directly convert the binary
document.writeln(parseInt("[email protected]")+"<br>");
//Execution results
4555
0
1221
12
NaN
Using parseInt, you can also easily achieve binary conversion. (parseFloat() is similar to parseFlaot, no more examples are given here.)
The code copy is as follows:
document.writeln(parseInt("0421",8)+"<br>");
document.writeln(parseInt("0421")+"<br>");
document.writeln(parseInt("0421",16)+"<br>");
document.writeln(parseInt("AF",16)+"<br>");
document.writeln(parseInt("011",10)+"<br>");
//Output result
273
421
1057
175
11