js中检测数据类型总结

2017-04-07  本文已影响0人  海洋lisle

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

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

注意:

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;
}

上一篇 下一篇

猜你喜欢

热点阅读