<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript基础:数据类型(boolean、number、string、Object、Undefined、Null)</title>
</head>
<body>
<!--
1、因为JavaScript是弱类型语言,故声明变量只需要使用var关键字即可申明任何类型的数据。
2、虽然var关键字即可申明任何类型的数据,但是JavaScript仍有数据类型。
boolean 布尔类型
number 数字类型
string 字符串类型
Object 对象类型
Undefined 未定义类型
Null 空对象类型
注意:Undefined类型和Null类型都是只有一个值的数据类型,值分别为undefined和null。
3、查看变量类型可以使用typeof方法。
-->
<script>
// 测试布尔变量的类型
var boolValue = true;
var boolType = typeof(boolValue);
alert("boolValue的类型是:" + boolType);
// 测试数字变量的类型
var numValue = 123;
var numType = typeof(numValue);
alert("numValue的类型是:" + numType);
// 测试字符串变量的类型
var strValue = "hello world !";
var strType = typeof(strValue);
alert("strValue的类型是:" + strType);
// 测试对象变量的类型
var objValue = Object;
var objType = typeof(objValue);
alert("objValue的类型是:" + objType);
// 测试undefined的类型
var undefinedValue = undefined;
var undefinedType = typeof(undefinedValue);
alert("undefinedValue的类型是:" + undefinedType);
// 测试空对象的类型
var nullValue = null;
var nullType = typeof(nullValue);
alert("nullValue的类型是:" + nullType);
</script>
</body>
</html>
页面弹出框分别显示以下信息:
boolValue的类型是:boolean
numValue的类型是:number
strValue的类型是:string
objValue的类型是:function
undefinedValue的类型是:undefined
nullValue的类型是:object
有2个数值是在预料之外:
Object被认为是function类型,null被认为是object类型。