typeof
typeof
操做符是肯定一个变量是String
、Number
、Boolean
,仍是undefined
的最佳工具
引用来源:《JavaScript高级程序设计》图灵程序设计丛书javascript
看下面例子:java
var s = 'hello'; var num = 10; var bool = true; var und; typeof s; // "string" typeof num; // "number" typeof bool; // "boolean" typeof und; // "undefined"
ok,都检测出来了,but, 若是检测的是一个对象
或者null
,就会会返回Object
,以下:
var n = null; var o = new Object(); typeof n; // "object" typeof o; // "object"
看吧,一点区分度也没有。函数
因此: 在 检测基本数据类型时,typeof很好用,在检测引用类型的值时,typeof的做用不大工具
instanceof
var o = new Object(); var arr = []; var reg = /^abc$/ o instanceof Object //true arr instanceof Array //true reg instanceof RegExp //true
注意:使用instanceof
操做符检测基本数据类型的值时,都会返回false
,尽管下面的例子看起来很矛盾prototype
null instanceof Object // false typeof null // "object"
Object.prototype.toString()
ECMA-262 规范中,toString
方法是这样定义的:设计
"[object Undefined]"
."[object Null]"
.它能够返回引用类型更精准的类型检测
var o = new Object(); var arr = []; var reg = /^abc$/ Object.prototype.toString.call(o) // "[object Object]" Object.prototype.toString.call(arr) // "[object Array]" Object.prototype.toString.call(reg) // "[object RegExp]"
经过函数封装处理一下:
var type = function (o) { var s = Object.prototype.toString.call(o); return s.match(/\[object (.*?)\]/)[1]; } type(o) // "Object" type(reg) // "RegExp" type(arr) // "Array"