javascript数据类型分为简单数据类型和复杂数据类型。简单数据类型分为string,number,boolean,defined,null,复杂数据类型为Object.类型检测在写代码可能会非常有用,下面是我对类型检查的一些探索。
用typeof检测:
var str = '123'; var num = 2; var boo = true; var def = undefined; var nu = null; var o = new Object(); var fn = function(){ var h =hello; } var arr = []; var ob = Object; typeof str //string typeof num //number typeof boo //boolean typeof def //undefined typeof nu //object typeof o //object console.log(typeof fn); //function console.log(typeof arr); //object console.log(typeof ob); //function
typeof在检测基本数据类型的时候看起来得心应手,但是在检测引用类型值时,通常它的作用不是很大。因为有时候我们不仅仅需要知道某个值是引用类型,更需要知道是什么引用类型
而typeof在检测引用类型的不可预测性。为此ecmascript提供了instanceof操作符。
用instanceof检测:
语法规则:result = variable instanceof contructor 通过原型链来进行识别
console.log(person instanceof Array); console.log(colors instanceof Object); console.log(patten instanceof RegExp);
由于所有引用类型的值都是Obejct的实例,大家可以看看这篇文章来学习一下原型链,所以instanceof在检测引用类型方面也不是非常安全。
用Object.prototype.toString()判断:
根据一些框架的源码的判断方法
function isFunction(it){ return Object.prototype.toString.call(it) === '[object Function]'; } function isArray(it){ return Object.prototype.toString.call(it) === '[object Array]'; }