1、数据类型
js中的数据大致分为几类:
数值型——number;
字符型——string;
布尔型——boolean:取值为true或者false;
null与undefined:null代表空值,它的类型为object;undefined代表未定义,所有未定义值的变量均为undefined,类型也为undefined;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var x = 123;
document.write(x + " " + typeof x + "<br>");
var y = "字符串";
document.write(y + " " + typeof y + "<br>");
var z = true;
document.write(z + " " + typeof z + "<br>");
var t = null;
document.write(t + " " + typeof t + "<br>");
var u = undefined;
document.write(u + " " + typeof u + "<br>");
</script>
<body>
</body>
</html>
2、类型转换
转换成string型一共有两种方法:
1、使用toString()函数:
x = x.toString(),但是无法转换null与undefined;
2、使用String()函数
x = String(x),这种函数可以转换任意数据类型转变为字符串类型
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var x = undefined;
x = String(x);
document.write(x + " " + typeof x + "<br>");
var y = null;
y = String(y);
document.write(y + " " + typeof y + "<br>");
</script>
<body>
</body>
</html>