Javascript typeof和instanceof判断数据类型

js有5种基本数据类型:数值型 (number)、字符串型(string)、逻辑型(boolean、无定义数据类型 (undefined)、空值(null);

另外还有3种复合数据类型,分别是:函数(function)、对象(object)、数组 (array)。

判断数据类型是经常的事情,比如:

基本数据类型:

var sStr = "kingwell";

var nNum = 2012;

var bBoo = false;

var uNde;

var nNu = null;

alert(typeof sStr);//输出 string;

alert(typeof nNum);//输出 number;

alert(typeof bBoo);//输出 boolen;

alert(typeof uNde);//输出 undefined;

alert(typeof nNu);//输出 null;

 

复合数据类型:

var fFun = function(){alert("Hi");}

var aArr = [];

var oObj = {};

 

如果这里我们用typeof的话,看下面的结果:

alert(typeof fFun);//输出 object;

alert(typeof aArr);//输出 object;

alert(typeof oObj);//输出 object;

 


都是输出object,所有这里要用instanceof,但是instanceof需要指名具体的类型

alert(fFun instanceof Function);//输出 true;

alert(aArr instanceof Array);//输出 true;

alert(oObj instanceof Object);//输出 true;

 

 

posted @ 2012-09-09 08:59  kingwell  阅读(838)  评论(0)    收藏  举报