js中检测数据类型总结

有以下几种方法,前三种比较常用。第三种是最好的。

  • typeof
  • instanceof
  • Object.prototype.toString()
  • constructor
  • duck type

typeof

typeof非常适合函数对象 和基本数据类型的判断

typeof 100          //'number'
typeof true         //'boolean'
typeof function     //'function'
typeof undefined    //'undefined'
typeof null         //'object'
typeof NaN          // 'number'
typeof new Object() //'object'
typeof new String("123")    //'object'

instanceof

主要用于判断对象数据类型;object instanceof Object,左边必须是对象,否则返回false;右边必须是函数对象,或函数构造器,否则报错。

用来判断左边对象的原型链上是否有右边这个构造器;

[1,2,3] instanceof Array //true
new Object instanceof Array //false
'123' instanceof String     //false
new String('hi') instanceof String //true

注意:

  • 跨iframe和跨window不可以用instanceof
  • 无法检测null

Object.prototype.toString

Object.prototype.toString.apply([]) === "[object Array]"
Object.prototype.toString.apply(function(){}) === "[object Function]"
Object.prototype.toString.apply(null) === "[object Null]"
Object.prototype.toString.apply(undefined) === "[object undefined]"
Object.prototype.toString.apply('HI') === "[object String]"

可以处理null的问题;但是IE8以下会失效

附: jQuery下jQuery.type()的实现:

var class2type = {} ;
"Boolean Number String Function Array Date RegExp Object Error".split(" ").forEach(function(e,i){
    class2type[ "[object " + e + "]" ] = e.toLowerCase();
}) ;
//当然为了兼容IE低版本,forEach需要一个polyfill,不作细谈了。
function _typeof(obj){
    if ( obj == null ){
        return String( obj );
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ class2type.toString.call(obj) ] || "object" :
        typeof obj;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容