类型判断
返回类型:typeof
var o; document.write( typeof o ); //结果:undefined var s = "字符串"; document.write( typeof s ); //结果:string var i = 100; document.write( typeof i ); //结果:number var bol = true; document.write( typeof bol ); //结果:boolean function fun(){} document.write( typeof fun ); //结果:function var arr = [1,2]; document.write( typeof arr ); //结果:object var obj = {a:"a1", b:"b1"} document.write( typeof obj ); //结果:object var dt = new Date(); document.write( typeof dt ); //结果:object 注:typeof 对数组、时间类型,判断都是对象,最好用constructor返回构造函数返回构造:constructor
var o; // 注意:不能测试未赋值的变量 var s = "字符串"; document.write( s.constructor ); //结果:function String() { [native code] } var i = 100; document.write( i.constructor ); //结果:function Number() { [native code] } var bol = true; document.write( bol.constructor ); //结果:function Boolean() { [native code] } function fun(){} document.write( fun.constructor ); //结果:function Function() { [native code] } var arr = [1,2]; document.write( arr.constructor ); //结果:function Array() { [native code] } var obj = {a:"a1", b:"b1"} document.write( obj.constructor ); //结果:function Object() { [native code] } var dt = new Date(); document.write( dt.constructor ); //结果:function Date() { [native code] }constructor判断方法:
if(s.constructor === String){ // 是字符串 }