javascript中有五种基本数据类型:
1. string(字符类型);
2. Number(数值);
3. Null(空值,表示一个空对象指针);
4. Boolen(布尔值)
5. Undefined(一个值,特殊类性值)
还有一种复杂的数据类型Object
下面举个例子直观的理解下:
<script>
var a, b = null, c = "", d = 21, e = true, f = function () { }, g = undefined, h=0;
var i=new Object();
alert(typeof a);//undefined
alert(typeof b);//object
alert(typeof c);//string
alert(typeof d);//number
alert(typeof e);//boolean
alert(typeof f);//function
alert(typeof g);//undefined
alert(typeof h);//number
alert(typeof i);//object
</script>
对上面代码分析,首先要了解typeof 操作符,typeof不是内置函数
在javascript中,typeof操作符用来检测给定数据的类型,常常返回以下值:
string
number
boolean
object
undefined
function
根据typeof操作符,来对上面代码做一个分析:
alert(typeof b)为什么返回的是object,而不是undefined呢?
null和undefined是数据类型中都只有一个值的类型,实际上undefined值是派生自null值的,但为什么 typeof(undefined)返回的是undefined呢? 原因在于null值,在逻辑角度上来看表示的是一个空对象指针,这也是typeof操作符检测null时会返回“object”的原因。
注意:再给变量声明前,只要意在保存对象的变量还没有真正保存对象,就应该明确地让该变量保存null值,没有必要给变量显示的声明undefined。