JavaScript类型检测详解

JavaScript类型检测

本篇介绍一下如何检测JavaScript各种类型。

• 5种原始类型
• 对象
• Function
• Array
• 属性

5种原始类型
JavaScript中5种原始类型为string,number,boolean,undefined,null

var name = "Jack";
var age = 32;
var single = false;
var app;    //undefined

console.log(typeof name);   //string
console.log(typeof age);    //number
console.log(typeof single); //boolean
console.log(typeof app);    //undefined
console.log(typeof null);   //object

发现除null外的其他4种基本类型均可以用typeof来识别:

if(typeof name === "string") { name += "Zhang"; }
if(typeof age === "number") { age++; }
if(typeof single === "boolean" && single) { … }
if(typeof app === "undefined")  { app = {}; }

因为typeof null会得到object,所以直接用===来检测null:
if(el === null) { … }
对象
JavaScript的对象包括内置对象(Date,RegExp ,Error等)和自定义对象。
(注意,Function和Array虽然也都是内置对象,但下一节单独讲)
对象不能像基本类型那样用typeof来检测了,因为检测出来的结果都是object:

console.log(typeof new Date());    //object
console.log(typeof new RegExp());  //object
console.log(typeof new Error());   //object
console.log(typeof new Person());  //用typeof检测出自定义对象也是object

要改用instanceof来检测:

var date = new Date();
var reg = new RegExp();
var err = new Error();
var me = new Person();

if(date instanceof Date) {    //检测日期
    year = date.getFullYear(); 
}
if(reg instanceof RegExp) {    //检测正则表达式
    reg.test(...); 
}
if(err instanceof Error) {    //检测异常
    throw err; 
}
if(me instanceof Person) {    //检测自定义对象
    ... 
}

但自定义对象有个问题,假设浏览器frameA里和frameB里都定义了Person。 frameA里定义了me对象,用me instanceof Person检测出来为true。但当自定义对象me传给frameB后,在frameB里instanceof会是false。
本节一开头就说了,Function和Array虽然也都是内置对象,但留到下一节讲。原因就是Function和Array也有和自定义对象相同的上述问题。因此Function和Array一般不用instanceof

Function
上面说了用instanceof检测Function不能跨frame。因此用typeof来检测,它可跨frame:
var func = function(){};
if(typeof func === ‘function’) { … }
但IE8以前用typeof来检测DOM系函数会得到object,因此IE8以前改用in:

console.log(typeof document.getElementById);        //object,不是function
console.log(typeof document.getElementsByTagName);  //object,不是function
console.log(typeof document.createElement);         //object,不是function

//IE8以前的IE浏览器,要改用in来检测是否支持DOM函数

if("getElementById" in document) { … }        
if("getElementsByTagName" in document) { … }
if("createElement" in document) { … }

Array
上面说了用instanceof检测Array不能跨frame。ES5之前都自定义检测方法。其中最精确的方法:依赖Array的toString会返回固定字符串”[Object Array]”的事实来检测:

function isArray(arr) {
    return Object.prototype.toString.call(arr) === "[Object Array]";
}

该方法精确且优雅,因此被很多库所采纳,最终在ES5被作为isArray方法引入了Array,参照MDN。现在你不需要自定义检测方法了,直接用isArray()即可。
其他检测方法,都各有缺陷,不能100%精确。但作为一种思路是可以借鉴的。例如依赖Array是唯一包含sort方法的对象的事实来检测:

function isArray(arr) {
    return typeof arr.sort === "function";
}

如果是自定义对象也定义了sort方法,该方法就失效了。
属性
检测属性是否在实例对象中应该用hasOwnProperty。如果你不关心属性是在实例对象中还是在原型对象中,可以简单点用in
例如检测字面量对象属性:

var Person = {
    name: "Jack",
    age: 33
};
if("name" in Person) { … }                 //true
if(Person.hasOwnProperty("name")) { … }    //true

例如实例对象属性:

var Person = function (name, age) {
    this.name = name;
    this.age = age;
};
Person.prototype.location = "Shanghai";

var me = new Person("Jack", 33)
if("name" in me) { … }                 //true
if(me.hasOwnProperty("name")) { … }    //true
if("location" in me) { … }             //true
if(me.hasOwnProperty("location")) { … }//false

除此之外其他方法都不好:

if (object[propName])            //Not Good,你怎么知道属性值不是0或1?
if (object[propName] === null)        //Not Good,你怎么知道属性值不是null?
if (object[propName] === undefined)    //Not Good,你怎么知道属性值不是undefined?

总结
**用typeof检测string,number,boolean,undefined,Function
用===检测null
用isArray()检测Array
用instanceof检测内置对象(除Function和Array)和自定义对象
用hasOwnProperty检测属性是否在实例对象中。如果你不关心属性是在实例对象中还是在原型对象中,可以简单点用in**

更多资源可以访问:去转盘;或者加QQ群一起讨论学习js,css等技术(QQ群:512245829)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值