关于参数部类判断的一个短暂的思考写法
关于参数类型判断的一个短暂的思考写法
关于参数类型判断的api设计也做了很多,jQuery,prototype,tangram也有了很多,今天写个刚才随便写的。贴上
/* 其实关键就是array类型的判断 参数设置为两个 @param elem 要判断的对象或者其他 @param type 是否匹配的对象类型 @当然也有预定 type参数的指定因为和typeof返回比较 所以是小写 */ function isRType(elem,type){ //首先去拿typeof elem var Etype = typeof elem; //安全性防范 如果type没有定义用!undefined == true if(!type){ //拿上面定义的typeof elem 去和undefined return Etype != 'undefined'; } //处理array类型 if(type === 'array' && (elem.hasOwnProperty && elem instanceof Array)){ //对应array类型的判断稍微复杂一点 //instanceof 验证原型对象和实例对象之间的关系 return true; } return Etype === type; //非array类型的之间判断就可以了 } //array类型判断 isRType([0,1,2],'array'); //true //string类型判断 isRType('a','string'); //true isRType('a','array'); //false //object判断 isRType(window,'array'); //false isRType(window,'object'); //false //number类型测试 isRType(1,'number'); //true isRType('1','number'); //false