
正文
js类型判断-丰富加好用
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一,
自己有时候写一些东西,要做类型判断,还有测试的时候,对于原生的和jQuery中的类型判断,实在不敢恭维,所以就写了一个好用的类型判断,一般情况都够用的。
function test(type) {
if(type === null || type === undefined) {
return type;
}
// 如果是对象,就进里面判断,否则就是基本数据类型
else if (type instanceof Object) { // js对象判断, 由于typeof不能判断null object,所以只能提前判断,互相补充
if(type instanceof Function) {
return 'Function';
}else if(type instanceof Array) {
return 'Array';
} else if(type instanceof RegExp){
return 'RegExp';
}else if(type instanceof Date) {
return 'Date';
}
// 判断是节点对象还是JQuery对象,很有用,新手一般来说分不清什么是什么类型
else if(type instanceof Node){
return 'Node';
}else if(type instanceof jQuery){
return 'jQuery';
}
else{
return 'Object';
}
}
// 基本数据类型
else {
return typeof type;
}
}
二,
原生的代码限制很多,
typeof只能判断基本数据类型外加undefied,Function。null会判断为object,Object和Array会判断为Object。
instanceof 只能判断对象
=== 可以判断null,undefined。
把上面三种方式组合起来,才能判断这些基本的类型。我有加入了另外几种类型判断,对于新手和老手,都是不错的工具。希望大家喜欢吧!






