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

时间:2023-01-10 09:59:59

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