1.typeof主要用于检测值的类型,对于原始 值类型的数据比较有效,但对于对象或者数组 null返回都是object
function type(o){
return (o===null)?"null":(typeof o);
}
2.对于对象、数组等复杂类型可以使用Object对象的constructor属性进行检测,但undefined和null特殊值不能够使用constructor
var o={}; alert(o.constructor == Object); //true
var a=[];alert(o.constructor==Array); //true
3. 特殊类型undefined和null,需要先转 为 布尔值;直接量需要加个小括号(),即()把值类型 转为 对象
var value=undefined;
alert(typeof value); //"undefined"
alert(value&&value.constructor);//undefined
var value=null;
alert(typeof value);//"object"
alert(value && value.constructor);// null
alert(10.constructor);//语法错误
alert((10).constructor);//Number
4.在框架窗口检测数组类型,使用constructor会有环境window不一致导致错误
var ifram=ducoment.createElement("iframe");//创建一个浮动框架
document.body.appendChild(iframe);//在文档中插入该框架
var A=window.frames[0].Array;// 获取浮动框架窗口包含的Array构造函数
var a=new A();//利用该浮动框架的Aarry构造函数创建数组对象
alert(a.constructor==Array);//false,浮动窗口和当前窗口属于不同的window,所以返回false
alert(a.constructor);//注意,这是是 返回Arrayde字符串提示
解决:[].toString() 返回字符串""
利用使用call()或apply()方法调用toString()返回的是字符串"[object Array]"
function isArray(o){
return Object.prototype.toString.call(o)==="[object Array]";
}
alert(isArray(a));//返回 true
5.获取[object class]必需调用对象Object的原型方法toString()
var d=new Date();
alert(d.toString());//返回当前UTC时间字符串
var d=new Date();
var m=Object.prototype.toString;
alert(m.apply(d))//返回字符串"[object Date]"
6.安全检测JavaScript基本数据类型和内置对象
function typeOf(o){
var _toString=Object.prototype.toString;
var _type={//返回字符串如下
"undefined":"undefined",
"number":"number",
"boolean":"boolean",
"string":"string",
"[object Function]":"function",
"[object Array]":"array",
"[object Date]":"date",
"[object RegExp]":"regexp",
"[object Error]":"error"
}
return _type[typeof o] || _type[ _toString.call(o)] || (o? "object":"null")//把值转为字符串,匹配返回字符串是否包含特定检测字符进行检测
}
使用:
var a=Math.abs;
alert(typeOf(a));// "function"