使用Object对象的toString()方法自定义判断数据类型方法

Object.prototype.toString方法返回对象的类型字符串

Object.prototype.toString.call(2)     //  "[object Number]"
Object.prototype.toString.call("")    // "[object String]"
Object.prototype.toString.call(true)  // "[object Boolean]"
Object.prototype.toString.call(undefined)     //  "[object Undefined]"
Object.prototype.toString.call(null)    // "[object Null]"
Object.prototype.toString.call(Math)  // "[object Math]"
Object.prototype.toString.call({})     //  "[object Object]"
Object.prototype.toString.call([])    // "[object Array]"

利用以上特性,可以构造一个比typeof运算符更准确的类型判断函数

var dataType = function(o){
    var s = Object.prototype.toString.call(o);
    return s.match(/[object (.*?)]/)[1].toLowerCase();
}

dataType([]);  //  "array"

专门判断某一个类型

['Null', 'Undefined', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Function', 'RegExp', 'NaN', 'Infinite'].forEach(function(item){
    dataType['is' + item] = function(o){
        return dataType(o) === item.toLowerCase();
    }
})

dataType.isObject({}) // true
原文地址:https://www.cnblogs.com/stone-it/p/7326946.html