1、typeof
2、instanceof
3、Object.prototype.toString
例如:
typeof 123//"number"
typeof "123"//"string"
typeof true //"boolean"
function func(){}
typeof func//"function"
typeof undefined //"undefined"
typeof window //"object"
typeof {}//"object"
typeof []//"object"
typeof null // "object"
typeof
是无法检测数组的,数组的本质是一种特殊的对象,检验数组要用intanceof
var o={};
var a=[];
o instanceof Array // false
a instanceof Array // true
Object.prototype.toString能检测出所有的类型,但IE6下undefined、null均为Object类型
变量 | 检测语句 | 结果 |
---|---|---|
var num = 123; | Object.prototype.toString.call(num) | ‘[object Number]’ |
var str = “abcdef”; | Object.prototype.toString.call(str) | ‘[object String]’ |
var bool = true; | Object.prototype.toString.call(bool) | ‘[object Boolean]’ |
var arr = [1,2,3,4]; | Object.prototype.toString.call(arr) | ‘[object Array]’ |
{name:“苏”,age:25}; | Object.prototype.toString.call(json) | ‘[object Object]’ |
var func = function(){console.log(‘this is function’);} | Object.prototype.toString.call(func) | ‘[object Function]’ |
var und = undefined; | Object.prototype.toString.call(und) | ‘[object Undefined]’ |
var nul = null; | Object.prototype.toString.call(nul) | ‘[object Null]’ |
var date = new Date(); | Object.prototype.toString.call(date) | ‘[object Date]’ |
var reg = / ^ [a-zA-Z]{5,20}$ /; | Object.prototype.toString.call(reg) | ‘[object RegExp]’ |
var err = new Error(); | Object.prototype.toString.call(err) | ‘[object Error]’ |
总结
Number、String、Boolean
类型变量的检测:typeof
Array、JSON、Function、Undefined、Null、Date、RegExp、Error 等 Object 和 Function
类型变量的检测:推荐使用Object.prototype.toString.call()